Update: Starting with (at least [1]) Windows 10 version 20H2
(I don't know that Windows Server version and build that corresponds to; run winver.exe
to check your version and build), the DeleteFile
Windows API function now exhibits synchronous behavior, which implicitly solves the problems with PowerShell's Remove-Item
and .NET's System.IO.File.Delete
/ System.IO.Directory.Delete
(but, curiously, not with cmd.exe
's rd /s
).
Remove-Item -Recurse
出乎意料的是异步,最终因为用于文件和目录删除的 Windows API 方法本质上是异步的 and Remove-Item
并不能解释这一点。
This 断断续续地,不可预测地以两种方式之一体现:
A 潜在的解决方法 is to reuse现有目录emptying它 - 而不是删除和重新创造 it.
然而,emptying目录与Get-ChildItem $OUT -Recurse | Remove-Item -Recurse
is also容易出现间歇性故障,尽管可能不太频繁。
该问题不仅影响 PowerShellRemove-Item
, 但是也cmd.exe
's rd /s
以及 .NET 的[System.IO.Directory]::Delete()
:
从 Windows PowerShell v5.1 / PowerShell Core 6.2.0-preview.1 / 开始cmd.exe
10.0.17134.407 / .NET框架4.7.03056,.NET核心2.1,neither Remove-Item
, nor rd /s
, nor [System.IO.Directory]::Delete()
工作可靠, 因为他们无法解释 Windows API 文件/目录删除函数的异步行为:
- PowerShell 核心错误报告
- cmd.exe错误报告
- .NET Core 错误报告
For a 自定义 PowerShell 函数提供了一个可靠的同步解决方法, see 这个答案.
[1] I've personally verified that the issue is resolved in version 20H2
, by running the tests in GitHub issue #27958 for hours without failure; this answer suggests that the problem was resolved as early as version 1909
, starting with build 18363.657
, but Dinh Tran finds that the issue is not resolved as of build 18363.1316
when removing large directory trees such as node_modules
. I couldn't find any official information on the subject.