Last active
September 29, 2025 01:50
-
-
Save Tjerbor/49c901aef8ee1249f2bb6297ed1679f1 to your computer and use it in GitHub Desktop.
Powershell script to delete empty folders recursively while ignoring specific file types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Used for deleting folders to the Recycling Bin. | |
| Add-Type -AssemblyName Microsoft.VisualBasic | |
| # File types to ignore. | |
| $excluded = @(".txt", ".ini") | |
| # Recursive deletion function | |
| function Delete-Folders-Recursively { | |
| param ( | |
| $DirectoryPath | |
| ) | |
| # Checks first if folder has subfolders. | |
| # If true, then invokes function on children before moving to next step. | |
| $subfolders = [System.Collections.Generic.List[string]]::new() | |
| Get-ChildItem -Directory -force -LiteralPath $DirectoryPath | % { $subfolders.add($_.FullName) } | |
| if ($subfolders.Count -gt 0) { | |
| $subfolders | % { Delete-Folders-Recursively $_ } | |
| } | |
| # After potential subfolders have been removed, | |
| # checks if current folder is empty except for ignored file types. | |
| # If true, folder will be counted as empty and will be deleted. | |
| if ((Get-ChildItem -force -LiteralPath $DirectoryPath | Where-Object { $excluded.IndexOf($_.Extension) -eq -1 }).count -eq 0) { | |
| # Prints the directory path of the folder which is about to be delted | |
| Write-Verbose -Message ("Removing {0}" -f $DirectoryPath) -Verbose | |
| # V1 | |
| # Irreversable deletion | |
| # Remove-Item -Force -Recurse -Confirm:$false -LiteralPath $DirectoryPath | |
| # V2 | |
| # Deletes folder to Recycling Bin | |
| [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($DirectoryPath, 'OnlyErrorDialogs', 'SendToRecycleBin') | |
| } | |
| } | |
| # V1 | |
| # Gets all Root subfolders and executes the recursive deletion on them, | |
| # leaving Root out of the process. | |
| # Get-ChildItem -Directory -force | % { Delete-Folders-Recursively $_.FullName } | |
| # V2 | |
| # Deletes all empty folders including Root. | |
| # (Although, will never happen with this version, as the script is located in Root.) | |
| Delete-Folders-Recursively $PSScriptRoot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment