How to recursively delete an entire directory with PowerShell 2.0?

前端 未结 18 2112
南旧
南旧 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:43

    Deleting an entire folder tree sometimes works and sometimes fails with "Directory not empty" errors. Subsequently attempting to check if the folder still exists can result in "Access Denied" or "Unauthorized Access" errors. I do not know why this happens, though some insight may be gained from this StackOverflow posting.

    I have been able to get around these issues by specifying the order in which items within the folder are deleted, and by adding delays. The following runs well for me:

    # First remove any files in the folder tree
    Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force
    
    # Then remove any sub-folders (deepest ones first).    The -Recurse switch may be needed despite the deepest items being deleted first.
    ForEach ($Subfolder in Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Select-Object FullName, @{Name="Depth";Expression={($_.FullName -split "\\").Count}} | Sort-Object -Property @{Expression="Depth";Descending=$true}) { Remove-Item -LiteralPath $Subfolder.FullName -Recurse -Force }
    
    # Then remove the folder itself.  The -Recurse switch is sometimes needed despite the previous statements.
    Remove-Item -LiteralPath $FolderToDelete -Recurse -Force
    
    # Finally, give Windows some time to finish deleting the folder (try not to hurl)
    Start-Sleep -Seconds 4
    

    A Microsoft TechNet article Using Calculated Properties in PowerShell was helpful to me in getting a list of sub-folders sorted by depth.

    Similar reliability issues with RD /S /Q can be solved by running DEL /F /S /Q prior to RD /S /Q and running the RD a second time if necessary - ideally with a pause in between (i.e. using ping as shown below).

    DEL /F /S /Q "C:\Some\Folder\to\Delete\*.*" > nul
    RD /S /Q "C:\Some\Folder\to\Delete" > nul
    if exist "C:\Some\Folder\to\Delete"  ping -4 -n 4 127.0.0.1 > nul
    if exist "C:\Some\Folder\to\Delete"  RD /S /Q "C:\Some\Folder\to\Delete" > nul
    

提交回复
热议问题