Skip to content

Removes empty folders from specified directories recursively or non-recursively (a Windows PowerShell script).

License

Notifications You must be signed in to change notification settings

auberginehill/remove-empty-folders

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

25 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Remove-EmptyFolders.ps1

OS: Windows
Type: A Windows PowerShell script
Language: Windows PowerShell
Description: Remove-EmptyFolders searches for empty folders from a directory specified with the -Path parameter. By default the search is limited to the first directory level (i.e. the search and removal of the empty folders is done non-recursively), but if a -Recurse parameter is added to the launching command, Remove-EmptyFolders will remove empty folders from the subdirectories as well (i.e. the search and removal is done recursively).

If deletions are made, a log-file (deleted_folders.txt by default) is created to $env:temp, which points to the current temporary file location and is set in the system (– for more information about $env:temp, please see the Notes section). The filename of the log-file can be set with the -FileName parameter (a filename with a .txt ending is recommended) and the default output destination folder may be changed with the -Output parameter. During the possibly invoked log-file creation procedure Remove-EmptyFolders tries to preserve any pre-existing content rather than overwrite the specified file, so if the -FileName parameter points to an existing file, new log-info data is appended to the end of that file.

To invoke a simulation run, where no folders would be deleted in any circumstances, a parameter -WhatIf may be added to the launching command. If the -Audio parameter has been used, an audible beep would be emitted after Remove-EmptyFolders has deleted one or more folders. Please note that if any of the parameter values (after the parameter name itself) includes space characters, the value should be enclosed in quotation marks (single or double) so that PowerShell can interpret the command correctly.
Homepage: https://github.com/auberginehill/remove-empty-folders
Short URL: http://tinyurl.com/zbug5ep
Version: 1.1
Sources:
Emojis: Emoji Table
Mekac: Get folder where Access is denied
Mike F Robbins: PowerShell Advanced Functions: Can we build them better?
Lee Holmes: Windows PowerShell Cookbook (O'Reilly): Get-FileHash script
Downloads: For instance Remove-EmptyFolders.ps1. Or everything as a .zip-file.

Screenshot

        screenshot

Parameters

πŸ“
  • Parameter -Path

    with aliases -Start, -Begin, -Folder, and -From. The -Path parameter determines the starting point of the empty folder analyzation. The -Path parameter also accepts a collection of path names (separated by a comma). It's not mandatory to write -Path in the remove empty folders command to invoke the -Path parameter, as is shown in the Examples below, since Remove-EmptyFolders is trying to decipher the inputted queries as good as it is machinely possible within a 40 KB size limit.

    The paths should be valid file system paths to a directory (a full path name of a directory (i.e. folder path such as C:\Windows)). In case the path name includes space characters, please enclose the path name in quotation marks (single or double). If a collection of path names is defined for the -Path parameter, please separate the individual path names with a comma. The -Path parameter also takes an array of strings for paths and objects could be piped to this parameter, too. If no path is defined in the command launching Remove-EmptyFolders the user will be prompted to enter a -Path value. How deeply the filesystem structure is analysed (and how deeply buried empty folders are deleted) is toggled with the -Recurse parameter.

  • Parameter -Output

    with an alias -ReportPath. Specifies where the log-file (deleted_folders.txt by default, which is created or updated when deletions are made) is to be saved. The default save location is $env:temp, which points to the current temporary file location, which is set in the system. The default -Output save location is defined at line 14 with the $Output variable. In case the path name includes space characters, please enclose the path name in quotation marks (single or double). For usage, please see the Examples below and for more information about $env:temp, please see the Notes section below.

  • Parameter -FileName

    with an alias -File. The filename of the log-file can be set with the -FileName parameter (a filename with a .txt ending is recommended, the default filename is deleted_folders.txt). During the possibly invoked log-file creation procedure Remove-EmptyFolders tries to preserve any pre-existing content rather than overwrite the specified file, so if the -FileName parameter points to an existing file, new log-info data is appended to the end of that file. If the filename includes space characters, please enclose the filename in quotation marks (single or double).

  • Parameter -Recurse

    If the -Recurse parameter is added to the command launching Remove-EmptyFolders, also each and every sub-folder in any level, no matter how deep in the directory structure or behind how many sub-folders, is searched for empty folders and all found empty folders regardless of the sub-level are deleted. For best results against nested empty folders, it is recommended to run Remove-EmptyFolders iteratively with the -Recurse parameter until no empty folders are found.

    If the -Recurse parameter is not used, the search is limited to the first directory level (i.e. the search is done non-recursively) and only empty folders from the first level (as indicated with the -Path parameter with the common command " dir", for example) are deleted.

  • Parameter -WhatIf

    The parameter -WhatIf toggles whether the deletion of folders is actually done or not. By adding the -WhatIf parameter to the launching command only a simulation run is performed. When the -WhatIf parameter is added to the command launching Remove-EmptyFolders, a -WhatIf parameter is also added to the underlying Remove-Item cmdlet that is deleting the directories in Remove-EmptyFolders. In such case and if indeed empty folder(s) was/were detected by Remove-EmptyFolders, a list of directory paths that would be deleted by Remove-EmptyFolders is displayed in console ("What if:"). Since no real deletions aren't made, the script will return an "Exit Code 1" (A simulation run: the -WhatIf parameter was used).

  • Parameter -Audio

    If this parameter is used in the remove empty folders command, an audible beep will occur, if any deletions are made by Remove-EmptyFolders.

Outputs

➑️
  • Deletes empty folders.

  • Displays results about deleting empty folders in console, and if any deletions were made, writes or updates a logfile (deleted_folders.txt) at $env:temp. The filename of the log-file can be set with the -FileName parameter (a filename with a .txt ending is recommended) and the default output destination folder may be changed with the -Output parameter.
  • Default values (the log-file creation/updating procedure only occurs if deletion(s) is/are made by Remove-EmptyFolders):
    1. Path Type Name
      $env:temp\deleted_folders.txt TXT-file deleted_folders.txt

Notes

⚠️
  • Please note that all the parameters can be used in one remove empty folders command and that each of the parameters can be "tab completed" before typing them fully (by pressing the [tab] key).

  • Please also note that the possibly generated log-file is created in a directory, which is end-user settable in each remove empty folders command with the -Output parameter. The default save location is defined with the $Output variable (at line 14). The $env:temp variable points to the current temp folder. The default value of the $env:temp variable is C:\Users\<username>\AppData\Local\Temp (i.e. each user account has their own separate temp folder at path %USERPROFILE%\AppData\Local\Temp). To see the current temp path, for instance a command

    [System.IO.Path]::GetTempPath()

    may be used at the PowerShell prompt window [PS>]. To change the temp folder for instance to C:\Temp, please, for example, follow the instructions at Temporary Files Folder - Change Location in Windows, which in essence are something along the lines:
    1. Right click on Computer and click on Properties (or select Start β†’ Control Panel β†’ System). In the resulting window with the basic information about the computer...
    2. Click on Advanced system settings on the left panel and select Advanced tab on the resulting pop-up window.
    3. Click on the button near the bottom labeled Environment Variables.
    4. In the topmost section labeled User variables both TMP and TEMP may be seen. Each different login account is assigned its own temporary locations. These values can be changed by double clicking a value or by highlighting a value and selecting Edit. The specified path will be used by Windows and many other programs for temporary files. It's advisable to set the same value (a directory path) for both TMP and TEMP.
    5. Any running programs need to be restarted for the new values to take effect. In fact, probably also Windows itself needs to be restarted for it to begin using the new values for its own temporary files.

Examples

πŸ“– To open this code in Windows PowerShell, for instance:

  1. ./Remove-EmptyFolders -Path "E:\chiore" -Output "C:\Scripts"
    Run the script. Please notice to insert ./ or .\ before the script name. Removes all empty folders from the first level of E:\chiore (i.e. those empty folders, which would be listed with the "dir E:\chiore" command, and if any deletions were made, saves the log-file to C:\Scripts with the default filename (deleted_folders.txt). During the possibly invoked log-file creation procedure Remove-EmptyFolders tries to preserve any pre-existing content rather than overwrite the file, so if the default log-file (deleted_folders.txt) already exists, new log-info data is appended to the end of that file. Please note, that -Path can be omitted in this example, because

    ./Remove-EmptyFolders "E:\chiore" -Output "C:\Scripts"

    will result in the exact same outcome.
  2. help ./Remove-EmptyFolders -Full
    Display the help file.
  3. ./Remove-EmptyFolders -Path "C:\Users\Dropbox", "C:\dc01" -Recurse -WhatIf
    Because the -WhatIf parameter was used, only a simulation run occurs, so no folders would be deleted in any circumstances. The script will look for empty folders from C:\Users\Dropbox and C:\dc01 and will add all sub-directories of the sub-directories of the sub-directories and their sub-directories as well from those directories to the list of folders to process (the search for other folders to process is done recursively).

    If empty folders aren't found, the result would be identical regardless whether the -WhatIf parameter was used or not. If, however, empty folders were indeed found, only an indication of what the script would delete ("What if:") is displayed.

    The Path variable value is case-insensitive (as is most of the PowerShell), and since the path names don't contain any space characters, they don't need to be enveloped with quotation marks. Actually the -Path parameter may be left out from the command, too, since, for example,

    ./Remove-EmptyFolders c:\users\dROPBOx, c:\DC01 -Recurse -WhatIf

    is the exact same command in nature.
  4. .\Remove-EmptyFolders.ps1 -From C:\dc01 -ReportPath C:\Scripts -File log.txt -Recurse -Audio
    Run the script and search recursively for empty folders from C:\dc01 and delete all recursively found empty folders under C:\dc01. If any deletions were made, the log-file would be saved to C:\Scripts with the filename log.txt and an audible beep would occur. This command will work, because -From is an alias of -Path and -ReportPath is an alias of -Output and -File is an alias of -FileName. Furthermore, since the path names don't contain any space characters, they don't need to be enclosed in quotation marks.
  5. Set-ExecutionPolicy remotesigned
    This command is altering the Windows PowerShell rights to enable script execution for the default (LocalMachine) scope. Windows PowerShell has to be run with elevated rights (run as an administrator) to actually be able to change the script execution properties. The default value of the default (LocalMachine) scope is "Set-ExecutionPolicy restricted".

    Parameters:

      Restricted Does not load configuration files or run scripts. Restricted is the default execution policy.
      AllSigned Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer.
      RemoteSigned Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.
      Unrestricted Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.
      Bypass Nothing is blocked and there are no warnings or prompts.
      Undefined Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy that is set in a Group Policy scope.

    For more information, please type "Get-ExecutionPolicy -List", "help Set-ExecutionPolicy -Full", "help about_Execution_Policies" or visit Set-ExecutionPolicy or about_Execution_Policies.

  6. New-Item -ItemType File -Path C:\Temp\Remove-EmptyFolders.ps1
    Creates an empty ps1-file to the C:\Temp directory. The New-Item cmdlet has an inherent -NoClobber mode built into it, so that the procedure will halt, if overwriting (replacing the contents) of an existing file is about to happen. Overwriting a file with the New-Item cmdlet requires using the Force. If the path name and/or the filename includes space characters, please enclose the whole -Path parameter value in quotation marks (single or double):

      New-Item -ItemType File -Path "C:\Folder Name\Remove-EmptyFolders.ps1"

    For more information, please type "help New-Item -Full".

Contributing

Find a bug? Have a feature request? Here is how you can contribute to this project:

contributing Bugs: Submit bugs and help us verify fixes.
Feature Requests: Feature request can be submitted by creating an Issue.
Edit Source Files: Submit pull requests for bug fixes and features and discuss existing proposals.

www

www Script Homepage
Mekac: Get folder where Access is denied
Mike F Robbins: PowerShell Advanced Functions: Can we build them better?
Lee Holmes: Windows PowerShell Cookbook (O'Reilly): Get-FileHash script
RemoveEmptyFolders.ps1
Remove all empty folders.ps1
Append Text to a File Using Add-Content in PowerShell
About Functions Advanced Parameters
PowerTip: Use PowerShell to Send Beep to Console
Get-FileHash.ps1
ASCII Art: http://www.figlet.org/ and ASCII Art Text Generator

Related scripts

www Disable-Defrag
Firefox Customization Files
Get-AsciiTable
Get-BatteryInfo
Get-ComputerInfo
Get-CultureTables
Get-DirectorySize
Get-HashValue
Get-InstalledPrograms
Get-InstalledWindowsUpdates
Get-PowerShellAliasesTable
Get-PowerShellSpecialFolders
Get-RAMInfo
Get-TimeDifference
Get-TimeZoneTable
Get-UnusedDriveLetters
Emoji Table
Java-Update
Remove-DuplicateFiles
Remove-EmptyFoldersLite
Rename-Files
Rock-Paper-Scissors
Toss-a-Coin
Update-AdobeFlashPlayer
Update-MozillaFirefox

About

Removes empty folders from specified directories recursively or non-recursively (a Windows PowerShell script).

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published