Home > other >  EventNames of PowerShell jobs started with Start-Job
EventNames of PowerShell jobs started with Start-Job

Time:01-30

I want to run a script when a PowerShell job has successfully completed. But how do I find out all possible events of the job started with the Start-Job cmdlet?

Here is an example:

$myjob = Start-Job { Get-ChildItem }

$jobEvent = Register-ObjectEvent -InputObject $myjob -EventName StateChanged -Action {
    Write-Host 'Job has completed'
}

So from some other examples on Stack Overflow I know that there is StateChanged event, but it only tells that a state of a job has changed. Is there any event that would tell that the job has failed or completed successfully?

How do I get a list of such events? Is there any event besides StateChanged?

Or does the code have to inspect the job using Get-Job after receiving the StateChanged event to determine the job's actual state?

CodePudding user response:

StateChanged is the only event you can subscribe to for the Job Class, it is enough though for what you're looking to accomplish.

In the Action block of your event there are different automatic variable that get automatically populated at event trigger: $Event, $EventArgs, $args, $EventSubscriber and $Sender which you can use to determine if your Job completed successfully or not. See about Automatic Variables for more details.

In this case I believe you could use the JobState.State Property from your Job and check if its equal to Completed. You could also check the .Reason property in case of a failure though this property may not always be populated.

$jobEvent = Register-ObjectEvent -InputObject $myjob -EventName StateChanged -Action {
    switch($EventArgs.JobStateInfo.State) {
        Completed { Write-Host ('Job [{0}] completed successfully.' -f $sender.InstanceId) -ForegroundColor Green }
        Failed { Write-Host ('Job [{0}] failed.' -f $sender.InstanceId) -ForegroundColor Red }
        Default { <# something else here, enum has many possible states #> }
    }
}
  • Related