PowerShell: Wait for the First command to finish


We know that PowerShell executes commands sequentially until we specify some parallel Jobs but sometimes the next command executes before the First command because the first command might be taking a long time to retrieve the data. In that case, if you want the previous command to finish first and then the next command to get executed, you can use PowerShell Job functionality.

For example, we need to write a script to ask for the user input to terminate process ID but the program should retrieve the process IDs first.

Example

$job = Start-Job {Get-Process}
Wait-Job $job | Out-Null
Receive-Job $job
$id = Read-Host "Enter the Process ID to terminate the Process "
Stop-Process -Id $id -PassThru -Verbose

In the above example, we are starting a PowerShell process job inside the Start-Job command and waiting for it to proceed further until it gets executed using the Wait-Jobcommand. Once Get-Process

command execution completes, the output will be displayed using the Receive-Job command and at the next, it asks for the process ID to get it terminate the specific process.

Updated on: 09-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements