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

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


当前回答

试试这个例子。如果目录不存在,则不会引发错误。您可能需要PowerShell v3.0。

remove-item -path "c:\Test Temp\Test Folder" -Force -Recurse -ErrorAction SilentlyContinue

其他回答

很简单:

remove-item -path <type in file or directory name>, press Enter

出于某种原因,约翰·里斯的回答有时对我不起作用。但它把我引向了下面的方向。 首先,我尝试使用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
        }
    }
}

在PowerShell $profile中添加一个自定义函数:

function rmrf([string]$Path) {
    try {
        Remove-Item -Recurse -ErrorAction:Stop $Path
    } catch [System.Management.Automation.ItemNotFoundException] {
        # Ignore
        $Error.Clear()
    }
}

这是rm -rf行为最准确的表示。

使用老式的DOS命令:

rd /s <dir>

当使用简单的删除项“文件夹”递归删除文件时,我有时会看到一个间歇性错误:[文件夹]不能删除,因为它不是空的。

这个答案试图通过单独删除文件来防止该错误。

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

一个重要的细节是使用pspath - descent对所有项进行排序,以便在根项之前删除叶项。排序是在pspath参数上完成的,因为它更有可能用于提供程序而不是文件系统。如果您想筛选要删除的项,则-Include参数只是一种方便。

它分为两个函数,因为我发现它可以通过运行来查看我将要删除的内容

Get-Tree some_dir | select fullname