To delete empty folders in PowerShell, you can use the Get-ChildItem cmdlet to retrieve the empty folders and then use the Remove-Item cmdlet to remove empty folders.
The following method shows how you can do it with syntax.
Method 1: Delete empty folders
Get-ChildItem -Recurse -Directory | Where-Object { (Get-ChildItem -Path $_.FullName).Count -eq 0} | Remove-Item -Recurse -Force
This example will delete all empty folders within folders and subfolders.
The following example shows how you can use this method.
Delete Empty Folders in the PowerShell
The following PowerShell script finds all empty folders and removes each one of them.
# specify the directory path $folderPath = "C:\temp\log\" # Find the empty folders $emptyFolders = Get-ChildItem -Path $folderPath -Recurse -Directory | Where-Object { (Get-ChildItem -Path $_.FullName).Count -eq 0} # remove empty folders $emptyFolders |Remove-Item -Recurse -Force
Output:
In this script, the Get-ChildItem cmdlet in PowerShell retrieves all directories recursively under the specified directory $folderPath and pipes them to the Where-Object cmdlet.
The Where-Object command filters out only the folders that contain no files or folders and stores the empty folders in the $emptyFolders variable.
Finally, the Remove-Item cmdlet deletes each empty folder forcefully and recursively.
In the screenshot, you can see the empty folders with names applog, Syslog, and winlog has been removed.
Conclusion
I hope the above article on deleting empty folders in PowerShell is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.