Home > Software design >  How to wait until each file is created within PowerShell?
How to wait until each file is created within PowerShell?

Time:06-16

I am using the following script to call an API to create a bunch of log files. It loops through all the first and second items in a text file (same way as how tokens are defined in CMD). This works fine:

$linesXmls = @(Get-Content -Path "$path") -Replace " "
ForEach($line in $lines) {
$s = $line -split ","
$var1s = $s[0]
$var2s = $s[1]
    Start-Process -FilePath $APIpath -ArgumentList "$argument1", "$argument2", "$argument3", "$path\folder\$var2s.log"
}

However this does not wait until the files are created before executing the next statement and causes my script to fail. Is there a way to wait before each $var2s log file is created?

CodePudding user response:

Start-Process is asynchronous, in the sense that it instructs the operating system to create and start a new process, and then immediately returns - a classic "fire-and-forget" mechanism.

For this reason, you may likely see that multiple processes are running simultaneously, which might caught issues with access to shared file resources.

To prevent such a race condition, use the -Wait swith parameter with Start-Process to force it to wait until the resulting process has exited until returning:

$linesXmls = @(Get-Content -Path "$path") -Replace " "
ForEach($line in $lines) {
    $s = $line -split ","
    $var1s = $s[0]
    $var2s = $s[1]
    Start-Process -FilePath $APIpath -ArgumentList "$argument1", "$argument2", "$argument3", "$path\folder\$var2s.log" -Wait
}
  • Related