DiamondDrake
DiamondDrake

Reputation: 1159

Powershell allow canceling of a start-process -wait

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.

Upvotes: 2

Views: 770

Answers (1)

DiamondDrake
DiamondDrake

Reputation: 1159

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!"
}

Upvotes: 1

Related Questions