header image

Removing empty folders

Posted by: | November 6, 2009 | No Comment |

I blogged about this a long time back. As part of my tidy up program (me? tidy up? – – stop laughing!) I’ve been moving scripts into PowerShell v2 modules.  I’ve added these three functions to my FileFunctions module.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
function Get-EmptyFolder {
    param (
    [string]$path = "C:\",
    [switch]$nodisplay
    )
   
## test folder path
    if (!(Test-Path -Path $path)){throw "Invalid path"}
   
    if (Test-Path "emptyfolders.txt"){Remove-Item emptyfolders.txt}
   
    $fso = New-Object -com "Scripting.FileSystemObject"
    Test-EmptyFolder $($fso.GetFolder($path))
    if (!$nodisplay){Get-Content emptyfolders.txt}
}

function Test-EmptyFolder{
    param ($folder)

    foreach ($subfolder in $folder.SubFolders){
        If ($subfolder.Size -eq 0) {Out-File emptyfolders.txt -inputobject $subfolder.Path  -append}

        Test-EmptyFolder $subfolder 
    }
}

function Remove-EmptyFolder{
    param (
    $file = "emptyfolders.txt",
    [switch]$remove
    )

    $folders = Get-Content $file 
    for ($i= $($folders.Length1); $i -ge 0; $i){
        if (!$remove) {Remove-Item $folders[$i] -WhatIf }
        else {Remove-Item $folders[$i] -verbose }
    } 
}

 

The Get-EmptyFolder function accepts a folder path and uses the Scripting.FileSystem object for the folder. This is passed to Test-EmptyFolder which tests the subfolders for size and adds the paths of empty ones to the output file. 

Test-EmptyFolder is then called recursively with each subfolder. Recursion is a very powerful technique for re-using the same function and looping through a nested structure.

A switch parameter is used to determine if the contents of the file should be displayed at the end. Switch parameters can be used to provide true\false values. In this case we display unless told not to.

The output file can then be processed by Remove-EmptyFolder. The file contents are read into an array which is then read bottom to top.  This enables me to delete subfolders before high level folders. Splitting the processing also allows me to review the file contents before folder removal.  As an additional check the –whatif parameter is used unless the -remove switch is used as a parameter.

The module manifest only publishes get-emptyfolder and remove-emptyfolder keeping test-emptyfolder as a hidden helper function.

I have a few more functions to add to this module then I’ll re-publish it on my sky drive.

Technorati Tags: ,,
under: PowerShell original