Is That Folder Empty?

In keeping with my recent trend of offering solutions based on PowerShell v2.0, here’s a function I’ve revised to test if a folder is empty. I can’t recall where I used the original function or if I ever did. But I came across it recently and decided to give it a facelift. Manually determining if a folder is empty is pretty easy. If it doesn’t have any files, I consider it empty. What I originally wanted was a way to find all empty folders, say from a given root folder. Once I’ve identified the folders I can do something with them like whack ‘em. Here’s my PowerShell v2 function.

Function IsEmptyFolder { <br/>#requires -version 2.0

&lt;# <br/>.Synopsis <br/>Determine if a folder is empty of all files. <br/>.Description <br/>This function can be used to determine if a folder is empty of all files. It will ignore any subfolders, unless that subfolder includes files. If the folder is empty, the fullname is written to the pipeline. You can capture this information to a file or variable or pass it on to Remove-Item to delete the folder. <br/>.Parameter Fullname <br/>The full folder path to examine <br/>.Example <br/>PS C:\&gt; IsEmptyFolder "c:\files\test" <br/><br/>Will return the folder full name if c:\files\test has no files. <br/>.Example <br/>PS C:\&gt; dir c:\test r-recurse | where {$_.PSIsContainer} | IsEmptyFolder | Sort <br/><br/>This is a bit more efficient as only directory paths are passed to the function. Output is sorted <br/>by the fullname. <br/>.Example <br/>PS C:\&gt; dir $env:temp -recurse | IsEmptyFolder | out-file Cleanup.txt <br/><br/>Find all empty folders in the %TEMP% directory and save the paths to a text file. <br/>.Example <br/>PS C:\&gt; dir $env:temp -recurse | IsEmptyFolder | Remove-Item -recurse <br/><br/>Find and delete all empty folders under %TEMP%. <br/>.Inputs <br/>Accepts strings or directoryinfo objects as pipelined input <br/>.Outputs <br/>[string] <br/><br/>.Link <br/>Get-ChildItem <br/><br/><br/>.Notes <br/>NAME: IsEmptyFolder Function <br/>VERSION: 1.0 <br/>AUTHOR: Jeffery Hicks <br/>LASTEDIT: 10/1/2009
<br/>#&gt;

[CmdletBinding()]
<br/>Param ( <br/>[Parameter(ValueFromPipeline=$True, <br/>ValueFromPipelineByPropertyName=$True, <br/>Position=1, <br/>Mandatory=$False, <br/>HelpMessage="Enter a folder name and path.")] <br/>[string[]]$fullname="." <br/>) <br/>
Begin { <br/>Write-Verbose "Starting function" <br/>Write-Debug "Starting function" <br/>Write-Debug "Running as $env:userdomain\$env:username"


} #end Begin

Process {

Trap {


Write-Warning "Failed to find or enumerate $fullname" <br/>Write-Verbose "Exception raised and caught by trap" <br/>Write-Debug "Exception raised and caught by trap" <br/>Write-Debug $_.Exception <br/>Continue


} <br/><br/>Write-Verbose "Testing $fullname" <br/>Write-Debug "Testing $fullname"

If ((dir $fullname -force -recurse -ea stop | where {-Not $_.PSIsContainer} | measure-object).Count -eq 0) { <br/>Write-Verbose "Writing empty folder fullname" <br/>Write-Debug "Empty folder found" <br/>if ($_) { <br/>Write-Debug "Current object is a $($_.GetType())" <br/>} <br/>#if a directory object was passed through the pipeline then we can use the object's full name. <br/>if ($_ -is [System.IO.DirectoryInfo]) {


write $_.Fullname <br/>} <br/>else { <br/>#otherwise write the value passed as a parameter <br/>write $fullname <br/>} <br/><br/>}
<br/>} #end Process

End {


Write-Verbose "Ending function" <br/>Write-Debug "Ending function"


} #end End

} #end function

The function takes advantage of integrated help that you can add in PowerShell v2.0. The comment block at the beginning defines a synopis, decription, parameter usage and examples. This is terrific because all I have to do is ask for help like any other cmdlet.

The function is pretty straight forward. You can give it a folder name as a parameter. If the folder is empty of file, including an subfolders that might contain files, then the filename is returned.

PS C:\&gt; IsEmptyFolder C:\test\empty <br/>C:\test\empty

Or you can pipe directory objects to the function.This is the more common scenario I would imagine.

PS C:\&gt; dir c:\test -recurse | where {$_.PSIsContainer} | IsEmptyFolder | Sort <br/>C:\test\common files\data b <br/>C:\test\empty <br/>C:\test\files <br/>C:\test\foo bar <br/>C:\test\foo bar\child <br/>C:\test\foo2 <br/>C:\test\nada\1\2

The ultimate goal would be to actually remove them.

PS C:\&gt; dir c:\test -recurse | where {$_.PSIsContainer} | IsEmptyFolder | del -recurse -whatif <br/>What if: Performing operation "Remove Directory" on Target "C:\test\empty". <br/>What if: Performing operation "Remove Directory" on Target "C:\test\files". <br/>What if: Performing operation "Remove Directory" on Target "C:\test\foo bar". <br/>What if: Performing operation "Remove Directory" on Target "C:\test\foo2". <br/>What if: Performing operation "Remove Directory" on Target "C:\test\common files\data b". <br/>What if: Performing operation "Remove Directory" on Target "C:\test\foo bar\child". <br/>What if: Performing operation "Remove Directory" on Target "C:\test\nada\1\2".

As you look through the function, you’ll see some Write-Verbose and Write-Debug expressions. Because I’m using [CmdletBinding()]
in the function, I can use the common parameters like -Verbose and -Debug. When these parameters are specified, the corresponding PowerShell commands are sent to the appropriate pipeline. This is a great way of adding debug or trace information into your v2 script or function from the very beginning.

Please test this thoroughly in a non-production environment, especially if you will be deleting anything. From my testing I think I’ve covered everything but if not, please let me know.

Download the function

Post to Twitter Post to Delicious Post to Facebook Post to StumbleUpon

This entry was posted in CommandLine, PowerShell v2.0, Scripting and tagged , , , . Bookmark the permalink.

Comments are closed.