Get Empty Folders PowerShell

Get Empty Folders PowerShell

Hello,

In a cleaning purpose, you may want to identify empty folders. To do that, we need to use the “Get-ChildItem” cmdlet :

Get Empty Folders PowerShell – My Test Folder

Get Empty Folders PowerShell - My Test Folder

Get Empty Folders PowerShell – My Test Folder

We can see that I prepared all possible cases, now, let’s dig :

Get Empty Folders PowerShell - Get-Member

Get Empty Folders PowerShell – Get-Member

Have a look at the two methods I outlined, they will allow us to check for child item in each folders that “Get-ChildItem” found :

  1. GetDirectories
  2. GetFiles

So now, we can to something like this :

Get-ChildItem -Recurse | Where-Object -FilterScript {($_.GetFiles().Count -eq 0) -and $_.GetDirectories().Count -eq 0} | Select-Object -ExpandProperty FullName

Get Empty Folders PowerShell – Final line

If you want less errors, you need to filter out all files that can’t contains files, if you want your code to work on PowerShell 2.0, you need to do it like that :

Get-ChildItem -Recurse | Where-Object -FilterScript {$_.PSIsContainer -eq $True} | Where-Object -FilterScript {($_.GetFiles().Count -eq 0) -and $_.GetDirectories().Count -eq 0} | Select-Object -ExpandProperty FullName
Get Empty Folders PowerShell - Exemple

Get Empty Folders PowerShell – Exemple

This oneliner will find all your empty folder, you can then delete/archive them.

If you don’t care with backward compatibility (PowerShell 3+) :

Get-ChildItem -Directory -Recurse | Where-Object -FilterScript {($_.GetFiles().Count -eq 0) -and $_.GetDirectories().Count -eq 0} | Select-Object -ExpandProperty FullName

Leave a Reply