使用 New-Item 创建目录的竞争条件?

发布于 2024-11-29 07:40:38 字数 317 浏览 0 评论 0原文

当调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独守阴晴ぅ圆缺 2024-12-06 07:40:38

我无法重现你的问题。

PS > New-Item "test" -itemType Directory -Force -Verbose | %{ Test-Path $_.FullName }
VERBOSE: Performing the operation "Create Directory" on target "Destination: C:\Users\Frode\Desktop\test".
True

New-Item 通过获取 DirectoryInfo - 父目录的对象,并将其称为 CreateSubDirectory,例如:

DirectoryInfo subdirectory = new DirectoryInfo(parentPath).CreateSubdirectory(childName);

我不是开发人员,但据我所知,这意味着它是一个阻塞调用,因为它等待 DirectoryInfo 对象返回。所以问题可能出在您的存储子系统上。

I cannot reproduce your problem.

PS > New-Item "test" -itemType Directory -Force -Verbose | %{ Test-Path $_.FullName }
VERBOSE: Performing the operation "Create Directory" on target "Destination: C:\Users\Frode\Desktop\test".
True

New-Item creates a new directory by getting a DirectoryInfo-object for the parent directory, and calling it's CreateSubDirectory, like:

DirectoryInfo subdirectory = new DirectoryInfo(parentPath).CreateSubdirectory(childName);

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.

睫毛上残留的泪 2024-12-06 07:40:38

尝试在另一个进程中运行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文