Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wait until each file is created within PowerShell?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading