Today is: 10 March, 2010

Powershell function to remove empty directories

I created the following recursive function to delete empty directories. I made it recursive instead of using the built-in recursive argument because I was working with large file system, and the file and directory "counting" that the recursive flag does was a bit cumbersom. The force flag on the get-childitem cmdlet will cause the cmdlet to discover hidden files.

function findolder($apath) {
    $items = get-childitem $apath -force
    foreach($fileordir in $items) {
        if($fileordir.PSIsContainer) {
            findolder($fileordir.FullName)
            $childrens = get-childitem $fileordir.FullName -force
            if($childrens -eq $null) {
                remove-item $fileordir.FullName
            }
        }
    }
}

findolder("G:\")