0

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!

1
  • please show a example. Commented Oct 3, 2017 at 14:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.