【问题标题】:Race condition creating directory with New-Item?使用新项目创建目录的竞争条件?
【发布时间】:2011-10-24 20:28:08
【问题描述】:

在调用 New-Item 以使用 UNC 路径在外部计算机上创建目录时,我看到了竞争条件。代码如下:

New-Item $target -itemType Directory -Force -Verbose |
        %{ Write-Host "Creating dir" $_.FullName }

之后立即使用 Test-Path 会返回 false。我放置了一个 Test-Path -> sleep for 1 seconds retry loop,在休眠 1 秒后,Test-Path 返回 true。

New-Item 是阻塞调用吗?调用 New-Item 后我是否应该等待?

【问题讨论】:

  • 我没有问题,得到的结果为 true: md \\server\share\newFolder;测试路径 \\server\share\newFolder
  • 同上,在这里创建目录并快速连续测试 50 次没有问题。也许你的网络共享有什么不寻常的地方(比如缓存层)?
  • @Niall 您是否针对 DFS 共享执行此操作?虽然我不知道为什么你会从一条指令到另一条指令去不同的共享......
  • 不,据我所知,这不是 DFS 共享(不是我的专业领域)。我运行了类似的测试,发现它运行良好,但是当在我们运行的部署脚本期间采取相同的操作时,我们看到有时可能需要多达 3 个睡眠/重试循环(每个 1 秒)才能识别创建的文件夹。也许部署脚本在服务器文件系统上施加了足够的负载,以至于可以看到一些缓存异常。不知道。

标签: windows powershell


【解决方案1】:

我无法重现您的问题。

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-object 来创建一个新目录,并将其命名为CreateSubDirectory,例如:

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

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

【讨论】:

    【解决方案2】:

    尝试在另一个进程中运行New-Item 命令并等待它:

    Start-Process powershell -Argument "-Command `"New-Item `"$myNewDir`" -ItemType `"directory`"`"" -NoNewWindow -Wait

    我正在编写一个脚本,该脚本将创建一个文件夹,然后将一个 7zip 存档写入该文件夹,但 7zip 会抱怨该目录不存在。这似乎解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2015-06-10
      • 1970-01-01
      • 2020-04-23
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多