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.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Function IsEmptyFolder {
#requires -version 2.0
<#
.Synopsis
Determine if a folder is empty of all files.
.Description
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.
.Parameter Fullname
The full folder path to examine
.Example
PS C:\> IsEmptyFolder "c:\files\test"
Will return the folder full name if c:\files\test has no files.
.Example
PS C:\> dir c:\test r-recurse | where {$_.PSIsContainer} | IsEmptyFolder | Sort
This is a bit more efficient as only directory paths are passed to the function. Output is sorted
by the fullname.
.Example
PS C:\> dir $env:temp -recurse | IsEmptyFolder | out-file Cleanup.txt
Find all empty folders in the %TEMP% directory and save the paths to a text file.
.Example
PS C:\> dir $env:temp -recurse | IsEmptyFolder | Remove-Item -recurse
Find and delete all empty folders under %TEMP%.
.Inputs
Accepts strings or directoryinfo objects as pipelined input
.Outputs
[string]
.Link
Get-ChildItem
.Notes
NAME: IsEmptyFolder Function
VERSION: 1.0
AUTHOR: Jeffery Hicks
LASTEDIT: 10/1/2009
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=1,
Mandatory=$False,
HelpMessage="Enter a folder name and path.")]
[string[]]$fullname="."
) Begin {
Write-Verbose "Starting function"
Write-Debug "Starting function"
Write-Debug "Running as $env:userdomain\$env:username"} #end Begin
Process {
Trap {
Write-Warning "Failed to find or enumerate $fullname"
Write-Verbose "Exception raised and caught by trap"
Write-Debug "Exception raised and caught by trap"
Write-Debug $_.Exception
Continue}
Write-Verbose "Testing $fullname"
Write-Debug "Testing $fullname"
If ((dir $fullname -force -recurse -ea stop | where {-Not $_.PSIsContainer} | measure-object).Count -eq 0) {
Write-Verbose "Writing empty folder fullname"
Write-Debug "Empty folder found"
if ($_) {
Write-Debug "Current object is a $($_.GetType())"
}
#if a directory object was passed through the pipeline then we can use the object's full name.
if ($_ -is [System.IO.DirectoryInfo]) {write $_.Fullname
}
else {
#otherwise write the value passed as a parameter
write $fullname
}
}
} #end Process
End {
Write-Verbose "Ending function"
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:\> IsEmptyFolder C:\test\empty
C:\test\empty
Or you can pipe directory objects to the function.This is the more common scenario I would imagine.
PS C:\> dir c:\test -recurse | where {$_.PSIsContainer} | IsEmptyFolder | Sort
C:\test\common files\data b
C:\test\empty
C:\test\files
C:\test\foo bar
C:\test\foo bar\child
C:\test\foo2
C:\test\nada\1\2
The ultimate goal would be to actually remove them.
PS C:\> dir c:\test -recurse | where {$_.PSIsContainer} | IsEmptyFolder | del -recurse -whatif
What if: Performing operation "Remove Directory" on Target "C:\test\empty".
What if: Performing operation "Remove Directory" on Target "C:\test\files".
What if: Performing operation "Remove Directory" on Target "C:\test\foo bar".
What if: Performing operation "Remove Directory" on Target "C:\test\foo2".
What if: Performing operation "Remove Directory" on Target "C:\test\common files\data b".
What if: Performing operation "Remove Directory" on Target "C:\test\foo bar\child".
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.