≡ Menu

PsTip# Find empty directories using Powershell

In this post I will show you how to query for empty folders/directories in windows computer using powershell. Empty directory/folder means it will not have anything inside it. So our logic is to find child items inside each directory and see if it returns any objects or not. If we get any objects back, the folder is not empty otherwise, it is.

Here is the code and usage example:

FileName : Get-EmptyDirectories.ps1

[cmdletbinding()]            
param(            
[string]$DirectoryName            
)            

$Directories = Get-ChildItem -Path $DirectoryName -Recurse | ? {$_.PSIsContainer -eq $true }            
foreach($Directory in $Directories) {            
$Items = Get-ChildItem -Path $Directory.FullName            
if(!$items) {            
Write-Host "$($Directory.Fullname) is empty"            
}            
}

Output:

Read this post if you want to find empty or zero sized files in the file system.

Comments on this entry are closed.

  • Atik April 29, 2013, 10:27 am

    Hi Sitaram,
    Seems this command will work only for local machines. I want to know how to check whether the folder on remote machine is empty or not. I will be calling this command from Java through Runtime.exec.
    Can you please help me out.
    Thanks.