Niall Connaughton
Niall Connaughton

Reputation: 16117

Race condition creating directory with 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?

Upvotes: 7

Views: 1117

Answers (2)

Fredrick
Fredrick

Reputation: 1310

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.

Upvotes: 0

Frode F.
Frode F.

Reputation: 54981

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.

Upvotes: 1

Related Questions