How to recursively delete an entire directory with PowerShell 2.0?

前端 未结 18 2136
南旧
南旧 2020-12-07 07:26

What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell? I am using PowerShell V2 in Windows 7.

I have learned from severa

18条回答
  •  不知归路
    2020-12-07 07:54

    When deleting files recursively using a simple Remove-Item "folder" -Recurse I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.

    This answer attempts to prevent that error by individually deleting the files.

    function Get-Tree($Path,$Include='*') { 
        @(Get-Item $Path -Include $Include -Force) + 
            (Get-ChildItem $Path -Recurse -Include $Include -Force) | 
            sort pspath -Descending -unique
    } 
    
    function Remove-Tree($Path,$Include='*') { 
        Get-Tree $Path $Include | Remove-Item -force -recurse
    } 
    
    Remove-Tree some_dir
    

    An important detail is the sorting of all the items with pspath -Descending so that the leaves are deleted before the roots. The sorting is done on the pspath parameter since that has more chance of working for providers other than the file system. The -Include parameter is just a convenience if you want to filter the items to delete.

    It's split into two functions since I find it useful to see what I'm about to delete by running

    Get-Tree some_dir | select fullname
    

提交回复
热议问题