Listing Folders Only (and Finding Special Folders)

by Jan 12, 2009

Get-Childitem returns both files and folders. If you just want to see folders, use a filter-based on folders that have a property called PSIsContainer, that is true. The following line lists all folders and subfolders in your Windows folder:

dir $env:windir -recurse| Where-Object { $_.PSIsContainer }

From here, you can add more filters to show folders with no files (but possibly sub-folders) in them:

dir $env:windir -recurse| Where-Object { $_.PSIsContainer } | 
Where-Object { $_.GetFiles().Count -eq 0 }

To find completely empty folders, use this approach:

dir $env:windir -recurse| Where-Object { $_.PSIsContainer } | 
Where-Object { (Dir $_.Fullname).Count -eq 0 }

And to find only folders that contain PowerShell scripts, slightly change the code:

dir $env:windir -recurse| Where-Object { $_.PSIsContainer } | 
Where-Object { @(Dir "$($_.Fullname)*.ps1" ).Count -ne 0 }

Don't worry if you get red error messages: it simply means you have no access permissions to certain folders. Use the ErrorAction parameter and set it to SilentlyContinue to get rid of these messages. The following line also outputs a yellow status message telling you which folder is currently examined:

dir $env:windir -recurse -EA SilentlyContinue | 
Where-Object { $_.PSIsContainer } |
Where-Object {
Write-Host -Foreground Yellow "Examining $($_.Fullname)..." @(Dir "$($_.Fullname)*.ps1" -EA SilentlyContinue).Count -ne 0
}

As it turns out, the yellow status messages interfere with the results. Using a progress bar is a lot smarter. The final line uses Write-Progress to report the progress in a separate panel:

$c=dir $env:windir -recurse -EA SilentlyContinue | 
Where-Object { $_.PSIsContainer } |
Where-Object {
Write-Progress "Examining $($_.Fullname)..." "Found $c Folders..." @(Dir "$($_.Fullname)*.ps1" -EA SilentlyContinue).Count -ne 0
} | Foreach-Object { $c++$_ }