使用 New-Item 创建目录的竞争条件?
当调用 New-Item 使用 UNC 路径在外部计算机上创建目录时,我看到了竞争条件。代码如下:
New-Item $target -itemType Directory -Force -Verbose |
%{ Write-Host "Creating dir" $_.FullName }
之后立即使用 Test-Path 返回 false。我放置了一个测试路径 ->睡眠 1 秒重试循环,睡眠 1 秒后,测试路径返回 true。
New-Item 是阻塞调用吗?致电 New-Item 后我是否需要等待?
I'm seeing a race condition when calling New-Item to create a directory on a foreign machine using a UNC path. The code is below:
New-Item $target -itemType Directory -Force -Verbose |
%{ Write-Host "Creating dir" $_.FullName }
Using Test-Path immediately afterwards returns false. I put a Test-Path -> sleep for 1 second retry loop and after sleeping for 1 second, Test-Path is returning true.
Is New-Item a blocking call? Should I expect to have to wait after calling New-Item?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我无法重现你的问题。
New-Item
通过获取 DirectoryInfo - 父目录的对象,并将其称为 CreateSubDirectory,例如:我不是开发人员,但据我所知,这意味着它是一个阻塞调用,因为它等待
DirectoryInfo
对象返回。所以问题可能出在您的存储子系统上。I cannot reproduce your problem.
New-Item
creates a new directory by getting a DirectoryInfo-object for the parent directory, and calling it's CreateSubDirectory, like:I'm not a developer, but AFAIK that means it's a blocking call, since it waits for an
DirectoryInfo
-object in return. So mabe the problem is with your storage subsystem.尝试在另一个进程中运行
New-Item
命令并等待:Start-Process powershell -Argument "-Command `"New-Item `"$myNewDir`" -ItemType `"directory `"`"" -NoNewWindow -Wait
我正在编写一个脚本,该脚本将创建一个文件夹,然后将 7zip 存档写入该文件夹,但 7zip 会抱怨该目录不存在。这似乎解决了这个问题。
Try running the
New-Item
command in another process and wait for it:Start-Process powershell -Argument "-Command `"New-Item `"$myNewDir`" -ItemType `"directory`"`"" -NoNewWindow -Wait
I was writing a script that would create a folder and then write a 7zip archive to the folder but 7zip would complain that the directory did not exist. This seemed to work around the issue.