0
votes

When I want to stop a Powershell-Script when it runs into an error, how should I stop the script?

-ErrorAction -Stop ..

try {
     foo.bar
catch{
    $ErrorMsg = "An error occured during foo.bar"
    Write-Error -Message $ErrorMsg -ErrorAction Stop
}

or

try {
     foo.bar
catch{
    $ErrorMsg = "An error occured during foo.bar"
    Write-Error -Message $ErrorMsg
    exit
}

What is Best Practise and recommened?

1
We haven't heard from you.. Did my answer solve your problem? If so, please consider accepting it by clicking the icon on the left. This will help others with a similar question finding it more easily.Theo

1 Answers

0
votes

You could set the $ErrorActionPreference to Stop beforehand, then call your script in the try{}. The script should use throw if it encounters an error that should terminate the script so it bubbles up to the calling script.

Something like

$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try {
     foo.bar
}
catch{
    # re-throw the exception
    throw
}
finally {
    # reset the ErrorActionPreference
    $ErrorActionPreference = $oldErrorAction
}