2
votes

I need to pause a powershell script until a process it started has finished. Great I can just use Start-Process xxxx -wait But there are a few cases where I need to be able to continue the script without waiting, and I can't make this decision before I start the process.

Preferable I would even be able to kill the started process here, but is there a way to start a process and then listen for enter key or "continue" that will stop the process and let the powershell script continue on and otherwise just wait for the process to finish and exit to continue the script?

I've been digging through the powershell docs for a couple hours and I'm having a hard time finding what commands best handle my problem.

aside, ideally this would be powershell 7 (core) cross platform compatible.

1
$p = Start-Process -Passthru then call $p. WaitForExit(2000) in a loop, and check the book result. If you need to kill the process call $p. Kill() - Moerwald
Thanks, this does sound like what I’m looking for, but if I’m going to accept input to possibly kill it won’t that block the loop from running again? - DiamondDrake
Using [Console::KeyAvailable] and a loop I can check it. But using start-process the input doesn't return to my powershell window until the process exits. I had to use -NoNewWindow to keep the input but it does seem to work - DiamondDrake

1 Answers

1
votes

This isn't guaranteed for everyone, but it worked for my case

Write-Host "  Waiting on synrchonize..."
$process = Start-Process "java" -NoNewWindow -argumentlist "-jar myjar.jar" -PassThru
Write-Host "  Press any key to skip wait"
while(!([Console]::KeyAvailable -or ($process.HasExited)))
{
    [Threading.Thread]::Sleep( 100 )
}

if(!$process.HasExited){
    Write-Host "...skipped"
    $process.Kill()
} else {
    Write-Host "...waited!"
}