Skip to content

Instantly share code, notes, and snippets.

@opentechnologist
Created July 16, 2023 03:27
Show Gist options
  • Save opentechnologist/fe7b7208c53694a08329f4b73428e2c9 to your computer and use it in GitHub Desktop.
Save opentechnologist/fe7b7208c53694a08329f4b73428e2c9 to your computer and use it in GitHub Desktop.
a simple PowerShell script to remove annoying empty directories.
<#
.SYNOPSIS
Recursively removes all empty directories.
.DESCRIPTION
This script locally traverses all existing directories starting from
the current directory and then employs a depth first removal of empty
directories.
For safety purposes, a `$dryrun` variable is set to `$true` to prevent
users from inadvertently removing empty directories on first run.
The variable must be set to `$false` to actually remove empty directories.
WARNING TO USERS:
There is no option to supply a target directory. Directory traversal
will always start from the current directory where the script was
initially executed.
There is no option to exclude a specific folder or set of directories.
It will simply remove all empty directories that it finds.
This script has not been tested on and may run very very slowly on
enormous and deeply nested directory structures.
#>
$dryrun=$true
Function Delete-EmptyFolder($Folder)
{
$items = Get-ChildItem -LiteralPath $Folder.FullName -Force
if ($items -eq $null) {
Remove-Item -LiteralPath $Folder.FullName -WhatIf:$dryrun
}
}
Get-ChildItem -Path . -Directory -Recurse -Force |
Sort-Object { $_.FullName.Length } -Descending |
Foreach-Object {
Delete-EmptyFolder -Folder $_
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment