PowerShell 删除项目不等待

2023-11-26

如果有这段代码

if(Test-Path -Path $OUT) 
{ 
    Remove-Item $OUT -Recurse 
}
New-Item -ItemType directory -Path $OUT

有时它可以工作,但有时 New-Item 行会产生一个权限被拒绝项目存在未授权访问错误错误。我认为这意味着之前的删除项目尚未完全执行,并且无法创建该文件夹,因为它仍然存在。

如果我在那里插入睡眠

if(Test-Path -Path $OUT) 
{ 
    Remove-Item $OUT -Recurse 
    Start-Sleep -s 1
}
New-Item -ItemType directory -Path $OUT

那么它总是有效。 如何强制删除项目以确保文件夹确实被删除? 或者也许我错过了其他东西?


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 断断续续地,不可预测地以两种方式之一体现:

  • 您的情况:删除后立即重新创建已删除的目录可能会失败,因为在尝试重新创建时删除可能尚未完成。

  • 更典型的是:如果在尝试删除父目录时子目录或文件的删除尚未完成,则删除非空目录本身可能会失败 - 这在服务器故障解答marsze 链接到。

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.exe10.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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PowerShell 删除项目不等待 的相关文章

随机推荐