How to Delete Empty Folders in PowerShell
It can be annoying when copying or moving large files from one location to another, only to find empty directories nested inside.
In this short post, you will discover how to remove recursively remove empty directories from the Windows PowerShell.
Using the PowerShell Remove-Item
cmdlet.
To delete empty folders in PowerShell, you can use the Remove-Item
cmdlet with the -Recurse
and -Force
flags, and specify the path to the root folder. You can also use the -Directory
flag to tell PowerShell that you only want to delete directories.
Remove-Item -Path <target_folder> -Recurse -Force
This will delete all empty directories under the target_folder
, including subdirectories.
You can also use the -Include
flag to specify a pattern for the directories you want to delete. For example, if you only want to delete directories that have names that start with dir
, you can use the following command:
Remove-Item -Path <target_folder> -Recurse -Force -Include dir*
Remember that the Remove-Item cmdlet will permanently delete directories, so be careful when using it. If you want to check which directories would be deleted without deleting them, you can use the -WhatIf
flag. This will show you a list of the directories that would be deleted without actually deleting them.
Remove-Item -Path <target_folder> -Recurse -Force -WhatIf
Using The PowerShell Get-ChildItem
Cmdlet
We can also combine the Get-ChildItem
, Where-Object,
and `Remove-Item Cmdlets to remove empty directories.
An example is as shown:
Get-ChildItem -Path <target_folder> -Recurse | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
Similarly, we can use the -Include
parameter of Get-ChildItem
to specify a pattern for the directories you want to delete. For example, if you only want to delete directories that have names that start with “dir”, you can use the following command:
Get-ChildItem -Path C:\Path\To\Root\Folder -Recurse -Include dir* | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
Closing
This tutorial covers two basic methods of recursively deleting empty files in Windows PowerShell. Feel free to leave us a comment down below and share!!