Creating race state with New-Item?

I see a race condition when calling New-Item to create a directory on a foreign machine using a UNC path. Code below:

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

Using Test-Path immediately returns false. I put Test-Path → sleep for 1 second of the repeat cycle and after sleep for 1 second Test-Path returns true.

Is New-Item a blocking call? Should I expect to wait after calling New-Item?

+7
source share
2 answers

I can not 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, receiving a DirectoryInfo object for the parent directory and calling CreateSubDirectory , for example:

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

I am not a developer, but AFAIK, which means that it is a blocking call, since it is waiting for the DirectoryInfo object to return. So the problem is with your storage subsystem.

0
source

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 wrote a script that would create a folder and then write the 7zip archive to the folder, but 7zip would complain that the directory does not exist. This seems like a problem.

0
source

All Articles