PowerShell

PowerShell: Search and delete empty Folders

Big Data? Pain? Looking for empty folders and want to delete them? In this post I show you how to proceed to find and delete empty folders.

Open PowerShell, ISE or VS Code.

Caution: If you proceed, all empty folders will be deleted without any warning.

Specify the root folder in line 1. In my example this is C:\Data. Then execute the PowerShell code.

All subfolders which are empty will be scanned and deleted without confirmation.

# Folder empty, then remove them

$path = 'C:\Data'

Get-ChildItem $path -Recurse -Directory | ForEach-Object {
    If((Get-ChildItem $_.FullName) -eq $null) {
        Remove-Item -Path $_.FullName -Confirm:$false -Verbose
    }
 }

The verbose parameter ensures that you can see everything that is happening.

Mission accomplished.

3 replies »

  1. Hi Patrick,
    Some comments about your code :

    – in a comparison, $Null should be in the left-hand side -cf https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-5.1)
    See the samples in the ref doc.
    In the present case, this doesn’t produce a bad result (only one object goes through the pipeline at a time), but I’m thinking it’s a bad practice to place $null on the right.

    – I’ve answered to a similar code recently in Reddit Powershell Sub. I’ve proposed the following code :

    $RootPath = “c:\temp”
    $FoldersList = Get-ChildItem -Path $RootPath -Directory -Recurse
    foreach ($Folder in $FoldersList)
    {
    if (-not (Get-ChildItem -Path $Folder -Recurse -ErrorAction Ignore))
    {# Folder is empty : no file, no sub-folder, remove it
    Remove-Item -Path $Folder.FullName -WhatIf # -Whatif is for test safely
    }
    }

    Another user said “When scanning a large volume of data it’s advised to avoid using a variable to gather all results of a recursive Get-ChildItem as it doesn’t leverage the pipeline. In some cases you might use too much memory to cache your results. Using a pipeline is a memory optimisation”.
    I agree with that, though we don’t know if it’s a large collection of data (these are directories that I put as variable, not files, there are probably many fewer).
    see for ref : https://new.reddit.com/r/PowerShell/comments/16e6mew/powershell_script_to_delets_all_empty_subfolders/

    Regards

    Liked by 1 person

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.