Kevin Price
Kevin Price

Reputation: 429

Powershell execute script block on exception

Im looking for a way in powershell to run a script block, or some code after an exception or a terminating write-error has occurred.

Basically, if I hit a throw, or a write-error, then I want the highest scope (main) to close out all PSSessions and do a get-job | remove-job before we stop execution.

Im not sure exactly if this is possible if I have set $ErrorActionPreference = "Stop"

This is what I came up with while waiting on an answer.. but Ill keep this question up incase someone has a better solution:

#Wait on feedback from children
try{
    While (Get-Job -State "Running")
    {
        Get-Job | Receive-Job
        Start-Sleep 2
    }
    Get-Job | Receive-Job
} finally {
    Get-PSSession | Remove-PSSession
    Get-Job | Remove-Job
}

thanks!

Upvotes: 0

Views: 299

Answers (1)

Persistent13
Persistent13

Reputation: 1562

Jobs will not send an error to the host by default, you'll need to throw an error manually.

#Wait on feedback from children
try{
    While (Get-Job -State "Running")
    {
        if (Get-Job -State 'Failed'){ throw 'Job failed.' }
        Get-Job | Receive-Job
        Start-Sleep 2
    }
    Get-Job | Receive-Job
} finally {
    Get-PSSession | Remove-PSSession
    Get-Job | Remove-Job
}

You may get more information about the failure by checking the JobState property on the job object.

Upvotes: 1

Related Questions