在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的各种示例,但这些示例通常基于过滤器删除一些文件集,而不是整个目录。

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


当前回答

出于某种原因,约翰·里斯的回答有时对我不起作用。但它把我引向了下面的方向。 首先,我尝试使用buggy -recurse选项递归地删除目录。然后,我进入剩下的每个子目录并删除所有文件。

function Remove-Tree($Path)
{ 
    Remove-Item $Path -force -Recurse -ErrorAction silentlycontinue

    if (Test-Path "$Path\" -ErrorAction silentlycontinue)
    {
        $folders = Get-ChildItem -Path $Path –Directory -Force
        ForEach ($folder in $folders)
        {
            Remove-Tree $folder.FullName
        }

        $files = Get-ChildItem -Path $Path -File -Force

        ForEach ($file in $files)
        {
            Remove-Item $file.FullName -force
        }

        if (Test-Path "$Path\" -ErrorAction silentlycontinue)
        {
            Remove-Item $Path -force
        }
    }
}

其他回答

rm -r ./folder -Force    

...为我工作

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终端上运行,当它完成时,它将停止。

受上面@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

要删除包括文件夹结构在内的完整内容使用

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}

在remove-item中添加的-递归确保交互式提示被禁用。

rm -r <folder_name>
c:\>rm -r "my photos"