Get-ChildItem -Directory -Recurse -Force, sorting those paths from deepest to shallowest by path length, checking each directory with Get-ChildItem -LiteralPath $_.FullName -Force, and passing truly empty folders to Remove-Item. Sorting from the deepest subfolder upward is essential: when a parent folder contains only empty subfolders, removing the child folders first makes the parent folder empty during the same pass so the entire empty branch is cleaned up at once. These commands work in both Windows PowerShell 5.1 (built into all supported builds of Windows 10 and Windows 11) and PowerShell 7.
Prerequisites and Safety Checks
Before running a recursive folder cleanup, verify your permissions, target path, and how PowerShell handles hidden files and deleted items.
- PowerShell version: Both Windows PowerShell 5.1 (
powershell.exe) and PowerShell 7 (pwsh.exe) support the-Directory,-Recurse,-Force,-LiteralPath, and-WhatIfparameters used in this guide. - Account permissions: Standard user privileges are sufficient for folders inside your user profile (such as
Documents,Downloads, or project folders). If you are cleaning shared directories, secondary drives with custom access control lists (ACLs), or system-wide paths, launch PowerShell using Run as administrator. - No Recycle Bin recovery:
Remove-Itempermanently deletes directories straight from the file system without sending them to the Windows Recycle Bin. Always run the preview commands first. - Hidden and system files: By default,
Get-ChildItemignores files with theHiddenorSystemattribute (such asdesktop.inior.gitmetadata). Every check in this guide includes the-Forceparameter onGet-ChildItemso a folder containing hidden files is never misidentified as empty. - Special characters in folder names: Folder names containing square brackets (
[or]) are treated as wildcard patterns by the standard-Pathparameter. Using-LiteralPathensures PowerShell treats every folder path as an exact string. - Safe target scope: Only run empty-folder cleanup against user data, archive, or media directories that you manage. Never run recursive empty-folder removal against
C:\Windows,C:\Program Files,C:\Program Files (x86),C:\ProgramData, or yourAppDatadirectory, as Windows and installed applications regularly rely on empty placeholder folders to function.
Step-by-Step: Preview and Remove Empty Folders in PowerShell
Step 1: Open PowerShell in Windows 10 or Windows 11
Launch a PowerShell session appropriate for the folder you want to clean:
- In Windows 11: Right-click the Start button and select Terminal (or Terminal (Admin) for protected folders). Ensure the active tab profile is set to Windows PowerShell or PowerShell.
- In Windows 10: Right-click the Start button and select Windows PowerShell (or Windows PowerShell (Admin)).
Step 2: Set and Verify Your Target Folder Path
Store your target directory in a variable so you only have to type or paste the path once and can verify it before running any scan.
- Run the following command, replacing
C:\Data\Projectswith the exact folder path you want to scan:
$TargetRoot = 'C:\Data\Projects' - Verify that the path exists and points to the right location:
Test-Path -LiteralPath $TargetRoot -PathType Container
Confirm that PowerShell returnsTruebefore continuing. If it returnsFalse, double-check the spelling and drive letter of$TargetRoot.
Step 3: Scan for Currently Empty Leaf Folders (Read-Only Preview)
Before changing anything on disk, scan the directory tree to see which folders currently contain zero files and zero subfolders.
- Run the following read-only command to list all currently empty folders:
Code:$EmptyLeafFolders = Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { @(Get-ChildItem -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue).Count -eq 0 } $EmptyLeafFolders | Select-Object FullName, LastWriteTime - Check the total count of empty leaf folders found:
$EmptyLeafFolders.Count - If the list is long or you prefer to inspect it in a sortable window, pipe the results to
Out-GridView(available in Windows PowerShell 5.1 and PowerShell 7 on Windows):
$EmptyLeafFolders | Select-Object FullName, CreationTime, LastWriteTime | Out-GridView -Title "Empty Leaf Folders Preview"
Step 4: Preview All Nested Empty Folder Trees That Will Become Empty
The scan in Step 3 only shows the deepest folders that are empty right now. If FolderA contains only FolderB, and FolderB is empty, FolderA is not technically empty until FolderB is removed. To preview every folder that will be removed—including parent folders that contain nothing except empty subfolders—check whether each directory contains any files (including hidden or system files) anywhere inside its subtree.
- Run this read-only command to list every folder in the hierarchy that contains zero files at any depth, sorted from deepest subfolder to shallowest parent:
Code:$AllEmptyTreeFolders = Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { @(Get-ChildItem -LiteralPath $_.FullName -File -Recurse -Force -ErrorAction SilentlyContinue).Count -eq 0 } | Sort-Object { $_.FullName.Length } -Descending $AllEmptyTreeFolders | Select-Object FullName, LastWriteTime - Optionally, save this preview list to a text file on your Desktop for record-keeping before deleting anything:
$AllEmptyTreeFolders.FullName | Out-File -FilePath "$HOME\Desktop\EmptyFoldersPreview.txt" -Encoding utf8
Step 5: Test the Removal Order Using -WhatIf
Before executing a live deletion, run Remove-Item with the -WhatIf switch. This simulates the exact bottom-up deletion pass and prints what PowerShell would do without removing any folders.
- Run the following command to simulate the bottom-up removal:
Code:Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force | Sort-Object { $_.FullName.Length } -Descending | Where-Object { @(Get-ChildItem -LiteralPath $_.FullName -Force).Count -eq 0 } | Remove-Item -Force -WhatIf - Review the
What if: Performing the operation "Remove Directory" on target "..."lines in the console. Because-WhatIfdoes not actually remove the deepest child folders during the simulation, only the currently empty leaf folders will triggerWhat if:messages during this dry run, while Step 4 already confirmed the full nested list.
Step 6: Remove the Empty Folders in Bottom-Up Order
Warning: The following command permanently deletes empty subfolders inside$TargetRoot. Deleted folders bypass the Recycle Bin and cannot be restored with Ctrl+Z in File Explorer. Ensure you have reviewed the output from Step 4 and confirmed that$TargetRootpoints to the intended directory.
- Run the bottom-up cleanup script. Because the
Where-Objectcheck evaluates each folder in real time after deeper subfolders have already been deleted in earlier iterations of the pipeline, parent folders that held only empty subfolders are automatically detected as empty and removed in the exact right order:
Code:Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force | Sort-Object { $_.FullName.Length } -Descending | ForEach-Object { if (@(Get-ChildItem -LiteralPath $_.FullName -Force).Count -eq 0) { Remove-Item -LiteralPath $_.FullName -Force -Verbose } } - Watch the yellow
VERBOSE: Performing the operation "Remove Directory" on target "..."output lines to see each empty folder removed from deepest child up to its parent directory. Notice that$TargetRootitself is never deleted becauseGet-ChildItemonly enumerates items inside$TargetRoot.
Verify That All Empty Folders Have Been Removed
After the cleanup completes, re-run the empty-folder check to confirm that no empty directories remain under $TargetRoot.
- Run the verification query:
Code:$RemainingEmpty = @( Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { @(Get-ChildItem -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue).Count -eq 0 } ) $RemainingEmpty.Count - A return value of
0confirms that every empty subfolder and nested empty directory branch under$TargetRoothas been removed. If the count is greater than0, display the remaining paths by running$RemainingEmpty.FullNameand consult the troubleshooting section below.
Alternate Method: Interactive Selection via Grid View
If your folder tree contains some intentional empty placeholder folders (such as Incoming, Output, or Temp folders required by a workflow) mixed in with leftover folders you want to delete, you can pick which empty leaf folders to delete interactively using Out-GridView -PassThru.
- Run the following command to open an interactive selection window listing all currently empty folders:
Code:Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force | Where-Object { @(Get-ChildItem -LiteralPath $_.FullName -Force).Count -eq 0 } | Select-Object FullName, CreationTime, LastWriteTime | Out-GridView -Title "Select Empty Folders to Delete and Click OK" -PassThru | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force -Verbose } - In the Grid View window that opens, hold Ctrl to click individual folders (or press Ctrl+A to select all of them, then Ctrl-click any placeholder folders you want to keep), and click OK in the bottom-right corner to remove only your selected folders.
Troubleshooting Common Errors and Rebuilding Folder Structures
Folders Appear Empty in File Explorer But PowerShell Does Not Remove Them
- Cause: The folder contains hidden operating system metadata files such as
desktop.ini(created when a folder has a custom icon or view setting) orThumbs.db(legacy thumbnail cache). Because our script usesGet-ChildItem -Forcefor safety, it refuses to delete folders containing hidden files so you do not accidentally lose hidden.git,.vs, or configuration files. - Fix: Inspect what hidden items are inside the folder by running:
Get-ChildItem -LiteralPath 'C:\Data\Projects\SubfolderName' -Force
If the only file inside is an unwanteddesktop.iniorThumbs.db, delete that specific metadata file first or remove it recursively across your data folder before re-running Step 6:
Get-ChildItem -LiteralPath $TargetRoot -Filter 'desktop.ini' -File -Recurse -Force | Remove-Item -Force -WhatIf
Remove-WhatIfonly if you do not care about losing custom folder icons or folder view customizations inside$TargetRoot.
Remove-Item : Access to the path is denied
- Cause: Either your user account lacks Modify/Delete permissions on the folder, the folder has the
ReadOnlyorSystemattribute combined with restricted ACLs, or a background process (such as Windows Search Indexer, an open command prompt, or a sync client) currently holds an open handle to the directory. - Fix: Close any File Explorer windows, code editors, or terminals currently open to that directory, and re-run the script in an elevated Windows PowerShell (Admin) or Terminal (Admin) window.
Cloud Sync Folders (OneDrive, SharePoint, or Dropbox) Refuse to Delete or Reappear
- Cause: Cloud-synced folders use NTFS reparse points and cloud filter placeholder metadata. Additionally, if a shared folder is actively synced, deleting it while the sync engine is updating can cause permission lock errors.
- Fix: Pause syncing briefly in the OneDrive or cloud client tray icon, run the cleanup script, and then resume syncing so the deletions propagate cleanly. Keep in mind that deleting synced folders removes them from your cloud storage and moves them to the cloud provider's web recycle bin.
Skipping Symbolic Links and Directory Junctions Safely
- Cause: If your folder tree contains NTFS junctions or directory symbolic links pointing to other locations on your drive,
Get-ChildItem -Recursein Windows PowerShell 5.1 can traverse into the linked target directory and evaluate subfolders outside your intended$TargetRoot. - Fix: Filter out reparse points (
Attributes -band [System.IO.FileAttributes]::ReparsePoint) so junctions and symbolic links are skipped entirely:
Code:Get-ChildItem -LiteralPath $TargetRoot -Directory -Recurse -Force | Where-Object { -not ($_.Attributes -band [System.IO.FileAttributes]::ReparsePoint) } | Sort-Object { $_.FullName.Length } -Descending | ForEach-Object { if (@(Get-ChildItem -LiteralPath $_.FullName -Force).Count -eq 0) { Remove-Item -LiteralPath $_.FullName -Force -Verbose } }
Recreating Deleted Empty Folders from Your Preview Log (Rollback)
Because Remove-Item deletes empty folders directly without sending them to the Recycle Bin, the fastest way to restore a required empty placeholder folder structure is from the EmptyFoldersPreview.txt file created in Step 4.
- To recreate every folder listed in your preview log, run:
Code:Get-Content -LiteralPath "$HOME\Desktop\EmptyFoldersPreview.txt" | ForEach-Object { if (-not (Test-Path -LiteralPath $_)) { New-Item -Path $_ -ItemType Directory -Force } } - If you only need to recreate a single placeholder directory that an application requires, run
New-Item -Path 'C:\Data\Projects\RequiredFolder' -ItemType Directory.