Thursday, November 5, 2015

Removing all empty folders in a Directory Tree using PowerShell

If you have a requirement to remove all empty folders in a Directory Tree using PowerShell, you might come across this article: https://technet.microsoft.com/en-us/library/ff730953.aspx

Unfortunately, this article has a major flaw in the script which ends up listing out BOTH the parent as well as the child subdirectories!!

Therefore, if you pipe the Remove-Item command to the results, you will end up removing the entire directory tree structure rather than just the empty folders!

Instead, you will want to modify the script to something like the following:
 
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$RootDir
)
 
Clear-Host
 
$emptyDir = Get-ChildItem $RootDir -Recurse | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0} | Select-Object $_.FullName
 
foreach ($emptyDirItem in $emptyDir)
{
    Write-Host $emptyDirItem.FullName
    Remove-Item $emptyDirItem.FullName
}#foreach

If instead, you prefer piping commands to each other, you can do something like the following:


[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$RootDir
)
 
Clear-Host
 
$emptyDir = Get-ChildItem $RootDir -Recurse | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0} | Select-Object $_.FullName `
| Remove-Item -Recurse #-WhatIf

That is all there is to it!

No comments:

Post a Comment