Thursday, November 6, 2014

IT: Find Empty Directories with Powershell

Today I was plugging along and got to use some PowerShell from the fine folks over at the PowerShell Tip Blog on Technet.

It's supposed to return a list of all of the empty directories in a path.
$a = Get-ChildItem C:\Scripts -recurse | Where-Object {$_.PSIsContainer
    -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName

Unfortunately, it really is only returning a list of all the directories with no files in them.  It will happily return a directory that has 100 other directories inside it. :(

This modified code returns a list of no-for-reals-I-mean-it empty directories... And it works!

$a = Get-ChildItem C:\Scripts -recurse | Where-Object {$_.PSIsContainer
    -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count
    -eq 0} | Select-Object FullName

No comments: