如何递归删除一个完整的目录与PowerShell 2.0?

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

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

554642 次浏览
Remove-Item -Recurse -Force some_dir

确实像广告上说的那样有效。

rm -r -fo some_dir

速记别名也有用吗?

据我所知,当你试图递归删除一组过滤过的文件时,-Recurse参数不能正确工作。杀死一个单一的目录和下面的一切似乎工作得很好。

使用老式的DOS命令:

rd /s <dir>

当使用简单的Remove-Item "folder" -Recurse递归删除文件时,我有时会看到一个间歇错误:[folder] cannot be removed because it is not empty.

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

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 -Descending对所有项进行排序,以便在根元素之前删除叶元素。排序是在pspath参数上完成的,因为它更有可能用于其他提供程序而不是文件系统。如果你想过滤要删除的项,-Include参数只是一个方便的方法。

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

Get-Tree some_dir | select fullname

我使用:

rm -r folderToDelete

这对我来说就像一个咒语(我从Ubuntu偷来的)。

很简单:

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

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

remove-item -path "c:\Test Temp\Test Folder" -Force -Recurse -ErrorAction SilentlyContinue
rm -r ./folder -Force

...为我工作

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

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

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

另一个有用的技巧:

如果你发现很多文件有相同或相似的命名约定(比如mac文件用点前缀命名…你可以很容易地从powershell中删除它们,就像这样:

ls -r .* | rm

这一行将删除当前目录中名称开头带有点的所有文件,以及该目录中其他文件夹中具有相同情况的所有文件。使用时要注意。: D

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

删除整个文件夹树有时有效,有时失败,会出现“目录非空”错误。随后尝试检查文件夹是否仍然存在可能会导致“访问被拒绝”或“未经授权的访问”错误。我不知道为什么会发生这种情况,尽管可以从这篇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可靠性问题可以通过在Rd / s / q之前运行Del / f / s / q并在必要时第二次运行理查德·道金斯来解决——理想情况下在两者之间有一个暂停(即如下所示使用)。

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

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

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

-recurse添加到remove-item确保交互式提示被禁用。

$users = get-childitem \\ServerName\c$\users\ | select -ExpandProperty name


foreach ($user in $users)


{
remove-item -path "\\Servername\c$\Users\$user\AppData\Local\Microsoft\Office365\PowerShell\*" -Force -Recurse
Write-Warning "$user Cleaned"
}

写上面的清理一些日志文件而不删除父目录,这工作完美!

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

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

因为底层文件系统是异步的,所以在Windows上Remove-Item -Force -Recurse可能会间歇性失败。这个答案似乎解决了这个问题。用户还积极参与了Powershell团队GitHub上

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

rm -r -fo targetDir

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

rmdir /s/q targetDir

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

基于@John里斯回答,并进行了一些改进。

初始文件树。/ 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

树。/ f

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


No subfolders exist

虽然rm -r的结果很好,但下面的方法更快:

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

为了测试这一点,你可以很容易地创建一个包含X个文件的文件夹(我使用:磁盘工具来快速生成文件)。

然后运行每个变量,使用:

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。我建议在目标文件系统上进行测试,看看哪种方法最适合您。

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

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

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