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?
StateChangedis the only event you can subscribe to for theJobClass, it is enough though for what you're looking to accomplish.In the
Actionblock of your event there are different automatic variable that get automatically populated at event trigger:$Event,$EventArgs,$args,$EventSubscriberand$Senderwhich 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.StateProperty from your Job and check if its equal toCompleted. You could also check the.Reasonproperty in case of a failure though this property may not always be populated.