删除整个文件夹树有时会起作用,有时会失败,并显示“目录不为空”错误。随后尝试检查该文件夹是否仍然存在,可能会导致“访问被拒绝”或“未经授权的访问”错误。我不知道为什么会发生这种情况,尽管可以从StackOverflow发布中获得一些见解。
通过指定删除文件夹中项目的顺序以及添加延迟,我已经能够解决这些问题。以下对我来说运行良好:
# 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
Microsoft TechNet上的文章在PowerShell中使用计算属性对我获得按深度排序的子文件夹列表很有帮助。
可以通过在RD / S / Q之前运行DEL / F / S / Q并在必要时第二次运行RD来解决RD / S / Q的类似可靠性问题-理想的是在两者之间稍作停顿(即,如图所示使用ping下面)。
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
RD /S /Q