1

I'm trying to capture error from command into variable and to exit script if error occures

Add-DistributionGroupMember -Identity [email protected] -Member `
[email protected] -ErrorAction stop -ErrorVariable MyError `
if ($MyError.Count -gt 0) {`
exit

} 

But MyError variable is empty and script continues to run,

if however, specify -ErrorAction SilentlyContinue then script simply continues and error variable is empty

5
  • 1
    is there a reason NOT to use try/catch? Commented Mar 27, 2020 at 15:25
  • yes, this code is already included in one bigger try/catch Commented Mar 27, 2020 at 15:28
  • 1
    You can nest try/catch, so could wrap the call to Add-DistributionGroupMember in its own one that exits if it catches anything. Commented Mar 27, 2020 at 15:33
  • 2
    the try/catch construct is not intended for big chunks of code. [grin] if you have a large chunk of code wrapped in a single try/catch ... you are doing it wrong. the construct is designed for catching errors as they happen ... not for "oh, look, and error happened somewhere" situations. Commented Mar 27, 2020 at 15:34
  • ok, i'll try with try/catch Commented Mar 27, 2020 at 22:09

1 Answer 1

1

As already mentioned in the comment, you should use a nested try catch block for the specified cmdlet, like this:

try
{
Add-DistributionGroupMember -Identity [email protected] -Member `
[email protected] -ErrorAction stop -ErrorVariable MyError `
}
catch {
      if($MyError.Count -gt 0)
      {
        Write-Output $myerror

        #if you want to exit execution after this error, use exit command as blow
        exit
      }
      }
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.