如何使用PowerShell 2.0递归删除整个目录?

458
什么是在PowerShell中强制删除目录及其所有子目录的最简单方法?我正在使用Windows 7中的PowerShell V2。
我从多个来源了解到,最明显的命令Remove-Item $targetDir -Recurse -Force不能正确工作。这包括PowerShell V2在线帮助中的一条语句(使用Get-Help Remove-Item -Examples找到),该语句如下:
“...因为此 cmdlet 中的 Recurse 参数存在故障,所以该命令使用 Get-Childitem cmdlet 获取所需文件,并使用管道运算符将它们传递给 Remove-Item cmdlet …”
我看到各种示例使用Get-ChildItem并将其导入Remove-Item,但这些示例通常基于过滤器删除某些文件集,而不是整个目录。
我正在寻找最干净的方法来清空整个目录,包括文件和子目录,而不使用任何用户警告消息,尽量少的代码。如果可以理解,一行代码就足够了。

2
PowerShell,我知道,但是 RD /S /Q - Rubens Farias
2
在PowerShell中似乎无法使用"RD /S /Q"命令,会提示"Remove-Item : A positional parameter cannot be found that accepts argument '/q'." - BrainSlugs83
8
在PowerShell中,rdRemove-Item的别名。但使用cmd /c "rd /s /q"也是可行的。 - codekaizen
2
我简直无法相信PowerShell会通过隐藏完全可用的MS-DOS命令来破坏基本功能!在CMD中,您可以使用rmdir或rd,但它们在PowerShell中都被劫持了。 - JonnyRaa
1
还有这个:https://dev59.com/fFQJ5IYBdhLWcg3wkG2-#53561052 - Andrew Savinykh
显示剩余2条评论
22个回答

4
在你的PowerShell $profile 中添加自定义函数:
function rmrf([string]$Path) {
    try {
        Remove-Item -Recurse -ErrorAction:Stop $Path
    } catch [System.Management.Automation.ItemNotFoundException] {
        # Ignore
        $Error.Clear()
    }
}

这是关于 rm -rf 命令行行为最准确的表述。


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

或者

remove-item <dir> -Recurse -Force

如果您有一个巨大的目录,那么我通常会这样做:
while (dir | where name -match <dir>) {write-host deleting; sleep -s 3}

在另一个 PowerShell 终端上运行此命令,它将在完成时停止。

我承认你的监控想法可能很有用,但它几乎与在完成后仅打印消息没有什么不同。如果在停止Remove-Item时出现任何问题,你的循环将永远无法结束。 - Raúl Salinas-Monteagudo
@RaúlSalinas-Monteagudo 没错,但它绝对适用于生产或无人值守的应用场景。它必须足够小,以便有人可以轻松记住并快速输入,而不是运行复杂的.ps1文件到一个目录中。 - Gajendra D Ambi

3

我采用了另一种方法,受到@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

3

虽然 rm -r 命令可以得到良好的结果,但以下方法更快:

$fso = New-Object -ComObject scripting.filesystemobject
$fso.DeleteFolder("D:\folder_to_remove")

要测试这个,你可以轻松地创建一个带有X个文件的文件夹(我使用Disk Tools快速生成文件)。

然后使用以下命令运行每个变量:

Measure-Command {rm D:\FOLDER_TO_DELETE -r}
Measure-Command {Remove-Item -Path D:\FOLDER_TO_DELETE -Recurse -Force}
Measure-Command {rd -r FOLDER_TO_DELETE }
$fso.DeleteFolder("D:\folder_to_remove")
Measure-Command {$fso.DeleteFolder("D:\FOLDER_TO_DELETE")}

我测试文件夹的结果如下:

Remove-Item - TotalMilliseconds : 1438.708
rm - TotalMilliseconds : 1268.8473
rd - TotalMilliseconds : 739.5385
FSO - TotalMilliseconds : 676.8091

结果因系统而异,但在我的系统上,fileSystemObject 是最佳选项。建议在目标文件系统上进行测试,以确定哪种方法最适合你。


3

似乎存在问题,即Remove-Item -Force -Recurse在Windows上可能会间歇性地失败,因为底层文件系统是异步的。这篇回答似乎解决了它。该用户还积极参与了Powershell团队在GitHub上的活动。


2

要删除完整的内容,包括文件夹结构,请使用以下命令:

get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}
-recurse 添加到 remove-item 命令中可以确保交互提示被禁用。

2

另一个有用的技巧:

如果你发现有很多名字类似或相同命名规则的文件(比如带有点前缀名字的Mac文件...那个著名的文件污染),你可以使用PowerShell中的一行代码轻松地将它们全部删除,就像这样:

ls -r .* | rm

这行代码将会删除当前目录下所有以点号开头的文件,以及该目录下其他文件夹中同样情况的文件。使用时请注意。 :D


为什么不使用 rm -rf .* 呢?我没有 PowerShell 进行测试,但我认为它会起作用。 - Vini.g.fer
1
很简单;如果你从命令中删除“| rm”,你可以查看要删除的整个全景,等你确定后,再执行该命令。 - Daniel Alberto Lepe Ayala
顺便说一下,如果要删除以点开头但具有隐藏属性的文件(例如Mac上的文件),可以使用以下命令:ls -r -h .* | rm - Daniel Alberto Lepe Ayala

1
非常简单:
remove-item -path <type in file or directory name>, press Enter

你应该提供一个示例执行。 - indivisible

0

基于@John Rees答案并进行了一些改进。

初始文件tree . /f

C:\USERS\MEGAM\ONEDRIVE\ESCRITORIO\PWSHCFX
│   X-Update-PowerShellCoreFxs.ps1
│   z
│   Z-Config.json
│   Z-CoreFxs.ps1
│
├───HappyBirthday Unicorn
│       collection-of-unicorns-and-hearts-with-rainbows.zip
│       hand-drawing-rainbow-design.zip
│       hand-drawn-unicorn-birthday-invitation-template (2).zip
│       hontana.zip
│       Unicorn - Original.pdf
│       Unicorn-free-printable-cake-toppers.png
│       Unicorn.pdf
│       Unicorn.png
│       Unicorn2.pdf
│       Unicorn3.pdf
│       Unicorn4.pdf
│       Unicorn5.pdf
│       UnicornMLP.pdf
│
├───x
└───y

代码

function Get-ItemTree() {
    param (
        [Parameter()]
        [System.String]
        $Path = ".",

        [Parameter()]
        [System.String]
        $Include = "*",

        [Parameter()]
        [switch]
        $IncludePath,

        [Parameter()]
        [switch]
        $Force

    )
    $result = @()
    if (!(Test-Path $Path)) {
        throw "Invalid path. The path `"$Path`" doesn't exist." #Test if path is valid.
    }
    if (Test-Path $Path -PathType Container)
    {
        $result += (Get-ChildItem "$Path" -Include "$Include" -Force:$Force -Recurse) # Add all items inside of a container, if path is a container.
    }
    if($IncludePath.IsPresent)
    {
        $result += @(Get-Item $Path -Force) # Add the $Path in the result.
    }
    $result = ,@($result | Sort-Object -Descending -Unique -Property "PSPath") # Sort elements by PSPath property, order in descending, remove duplicates with unique.
    return  $result
}

function Remove-ItemTree {
    param (
        [Parameter()]
        [System.String]
        $Path, 

        [Parameter()]
        [switch]
        $ForceDebug
    )
    (Get-ItemTree -Path $Path -Force -IncludePath) | ForEach-Object{
        Remove-Item "$($_.PSPath)" -Force
        if($PSBoundParameters.Debug.IsPresent)
        {
            Write-Debug -Message "Deleted: $($_.PSPath)" -Debug:$ForceDebug
        }
    }
}

Write-Host "███ Test 1"
$a = Get-ItemTree "./Z-Config.json" -Force -Include "*" -IncludePath:$true # Tree of a file path. 1 element the file (IncludePath parameter = $true)
$a | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 2"
$b = Get-ItemTree "./Z-Config.json" -Force -Include "*" -IncludePath:$false # Tree of a file path. No Result (IncludePath parameter = $false)
$b | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 3"
$c = Get-ItemTree "." -Force -Include "*" -IncludePath:$true # Tree of a container path. All elements of tree and the container included (IncludePath parameter = $true).
$c | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Write-Host "███ Test 4"
$d = Get-ItemTree "." -Force -Include "*" -IncludePath:$false # All elements of tree, except the container (IncludePath parameter = $false).
$d | Select-Object -ExpandProperty PSPath | ConvertTo-Json
Write-Host

Remove-ItemTree -Path "./HappyBirthday Unicorn" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./x" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./y" -Debug -ForceDebug #Remove the contents of container and remove the container. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.
Remove-ItemTree -Path "./z" -Debug -ForceDebug #Remove file. -Debug Prints debug messages and -ForceDebug forces to prints messages if DebugPreference is SilentlyContinue.

Get-ChildItem -Force

输出

███ Test 1
"Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json"

███ Test 2

███ Test 3
[
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-CoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\z",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\y",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\X-Update-PowerShellCoreFxs.ps1",       
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\x",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\UnicornMLP.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn5.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn4.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn3.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn2.pdf",  
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.png",   
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.pdf",   
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn-free-printable-cake-toppers.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn - Original.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hontana.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawn-unicorn-birthday-invitation-template (2).zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawing-rainbow-design.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\collection-of-unicorns-and-hearts-with-rainbows.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx"
]

███ Test 4
[
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-CoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\Z-Config.json",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\z",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\y",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\X-Update-PowerShellCoreFxs.ps1",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\x",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\UnicornMLP.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn5.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn4.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn3.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn2.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn-free-printable-cake-toppers.png",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\Unicorn - Original.pdf",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hontana.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawn-unicorn-birthday-invitation-template (2).zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\hand-drawing-rainbow-design.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn\\collection-of-unicorns-and-hearts-with-rainbows.zip",
  "Microsoft.PowerShell.Core\\FileSystem::C:\\Users\\Megam\\OneDrive\\Escritorio\\pwshcfx\\HappyBirthday Unicorn"
]

DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\UnicornMLP.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn5.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn4.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn3.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn2.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn.png
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn-free-printable-cake-toppers.png
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\Unicorn - Original.pdf
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hontana.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hand-drawn-unicorn-birthday-invitation-template (2).zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\hand-drawing-rainbow-design.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn\collection-of-unicorns-and-hearts-with-rainbows.zip
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\HappyBirthday Unicorn
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\x
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\y
DEBUG: Deleted: Microsoft.PowerShell.Core\FileSystem::C:\Users\Megam\OneDrive\Escritorio\pwshcfx\z


    Directory: C:\Users\Megam\OneDrive\Escritorio\pwshcfx

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
la---           17/5/2021     1:57            272 X-Update-PowerShellCoreFxs.ps1
la---           14/5/2021    18:51            252 Z-Config.json
la---           17/5/2021     4:04          30931 Z-CoreFxs.ps1

tree . /f

C:\USERS\MEGAM\ONEDRIVE\ESCRITORIO\PWSHCFX
    X-Update-PowerShellCoreFxs.ps1
    Z-Config.json
    Z-CoreFxs.ps1

No subfolders exist

0
请尝试以下的PowerShell脚本。如果遇到类似"Remove-Item : The tag present in the reparse point buffer is invalid."的错误,该脚本将跳过当前文件/文件夹,继续执行下一个。
# Get a list of all the folders to be deleted
$foldersToDelete = Get-ChildItem -Directory -Path "C:\Path\To\Folders"

# Delete each folder recursively, skipping to the next file if stuck with an error
foreach ($folder in $foldersToDelete) {
    try {
        Remove-Item -Path $folder.FullName -Recurse -Force
    } catch {
        Write-Host "Failed to delete folder '$folder.FullName': $_"
        continue
    }
}

感谢您对Stack Overflow社区做出贡献的兴趣。这个问题已经有了相当多的答案,其中一个答案已经得到社区的广泛验证。您确定您的方法之前没有被提到过吗?如果是这样的话,能否解释一下您的方法有何不同,在什么情况下您的方法可能更好,并且/或者为什么您认为之前的答案不够满意。您能否友好地编辑您的答案并提供一个解释? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接