How to recursively remove all empty folders in PowerShell?

前端 未结 13 2688
野趣味
野趣味 2020-12-08 02:23

I need to recursively remove all empty folders for a specific folder in PowerShell (checking folder and sub-folder at any level).

At the moment I am using this scrip

相关标签:
13条回答
  • 2020-12-08 03:02

    Something like this works for me. The script delete empty folders and folders containing only folder (no files, no hidden files).

    $items = gci -LiteralPath E:\ -Directory -Recurse
    $dirs = [System.Collections.Generic.HashSet[string]]::new([string[]]($items |% FullName))
    for (;;) {
        $remove = $dirs |? { (gci -LiteralPath $_ -Force).Count -eq 0 }
        if ($remove) {
            $remove | rm
            $dirs.ExceptWith( [string[]]$remove )
        }
        else {
            break
        }
    }
    
    0 讨论(0)
提交回复
热议问题