How to do something if a job has finished How to do something if a job has finished powershell powershell

How to do something if a job has finished


You can either specifiy a name for the job using the -Name parameter:

Start-Job { Write-Host "hello"} -Name "HelloWriter"

And receive the job status using the Get-Job cmdlet:

Get-Job -Name HelloWriter

Output:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  --     ----            -------------   -----         -----------     --------             -------                  3      HelloWriter     BackgroundJob   Completed     True            localhost             Write-Host "hello"

Or you assign the Start-Job cmdlet to a variable and use it to retrieve the job:

$worldJob = Start-Job { Write-Host "world"}

So you can just write $woldJob and receive:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  --     ----            -------------   -----         -----------     --------             -------                  7      Job7            BackgroundJob   Completed     True            localhost             Write-Host "world" 

You also don't have to poll the Job state. Instead use the Register-ObjectEvent cmdlet to get notificated when the job has finished:

$job = Start-Job { Sleep 3; } -Name "HelloJob"$jobEvent = Register-ObjectEvent $job StateChanged -Action {    Write-Host ('Job #{0} ({1}) complete.' -f $sender.Id, $sender.Name)    $jobEvent | Unregister-Event}


Multiple possible ways here:

$Var = Start-Job { & K:\sample\kdp.cmd }

an then check

$Var.State

Or give the job a name

Start-Job { & K:\sample\kdp.cmd } -Name MyJob

and then check

Get-Job MyJob