在PowerShell中强制删除目录及其所有子目录的最简单方法是什么?我在Windows 7中使用PowerShell V2。

我从几个来源了解到,最明显的命令,Remove-Item $targetDir -Recurse -Force,不能正确工作。这包括PowerShell V2在线帮助中的语句(使用Get-Help Remove-Item -Examples找到),声明:

...因为这个cmdlet中的递归参数是错误的,该命令使用get - childitem cmdlet来获取所需的文件,并使用管道操作符将它们传递给Remove-Item cmdlet…

我见过使用Get-ChildItem并将其输送到remove - item的各种示例,但这些示例通常基于过滤器删除一些文件集,而不是整个目录。

我正在寻找最干净的方法来吹出整个目录,文件和子目录,而不生成任何用户警告消息使用最少的代码量。如果简单易懂,那么一行代码最好。


当前回答

受上面@john-rees的启发,我采取了另一种方法——尤其是当他的方法在某种程度上开始对我失败时。基本上递归的子树和排序文件的路径长度-删除从最长到最短

Get-ChildItem $tfsLocalPath -Recurse |  #Find all children
    Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} |  #Calculate the length of their path
    Sort-Object PathLength -Descending | #sort by path length descending
    %{ Get-Item -LiteralPath $_.FullName } | 
    Remove-Item -Force

关于-LiteralPath魔法,这里有另一个可能困扰你的问题:https://superuser.com/q/212808

其他回答

使用老式的DOS命令:

rd /s <dir>

为了避免“目录不是空的”错误的接受的答案,只需使用好的旧DOS命令,如前所述。用于复制粘贴的完整PS语法如下:

& cmd.exe /c rd /S /Q $folderToDelete

受上面@john-rees的启发,我采取了另一种方法——尤其是当他的方法在某种程度上开始对我失败时。基本上递归的子树和排序文件的路径长度-删除从最长到最短

Get-ChildItem $tfsLocalPath -Recurse |  #Find all children
    Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} |  #Calculate the length of their path
    Sort-Object PathLength -Descending | #sort by path length descending
    %{ Get-Item -LiteralPath $_.FullName } | 
    Remove-Item -Force

关于-LiteralPath魔法,这里有另一个可能困扰你的问题:https://superuser.com/q/212808

如果你致力于powershell,你可以使用这个,正如在接受的答案中解释的那样:

rm -r -fo targetDir

但我发现使用Windows命令提示符更快

rmdir /s/q targetDir

除了速度更快之外,使用命令提示符选项的另一个优点是它立即开始删除文件(powershell首先执行一些枚举),因此如果在运行时出现故障,您至少在删除文件方面取得了一些进展。

del <dir> -Recurse -Force # I prefer this, short & sweet

OR

remove-item <dir> -Recurse -Force

如果你有一个很大的目录,那么我通常会做的是

while (dir | where name -match <dir>) {write-host deleting; sleep -s 3}

在另一个powershell终端上运行,当它完成时,它将停止。