How to recursively remove all empty folders in PowerShell?

前端 未结 13 2691
野趣味
野趣味 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 02:54

    I wouldn't take the comments/1st post to heart unless you also want to delete files that are nested more than one folder deep. You are going to end up deleting directories that may contain directories that may contain files. This is better:

    $FP= "C:\Temp\"
    
    $dirs= Get-Childitem -LiteralPath $FP -directory -recurse
    
    $Empty= $dirs | Where-Object {$_.GetFiles().Count -eq 0 **-and** $_.GetDirectories().Count -eq 0} | 
    
    Select-Object FullName
    

    The above checks to make sure the directory is in fact empty whereas the OP only checks to make sure there are no files. That in turn would result in files nexted a few folders deep also being deleted.

    You may need to run the above a few times as it won't delete Dirs that have nested Dirs. So it only deletes the deepest level. So loop it until they're all gone.

    Something else I do not do is use the -force parameter. That is by design. If in fact remove-item hits a dir that is not empty you want to be prompted as an additional safety.

提交回复
热议问题