0

Can someone tell me why this simple script will not catch any exceptions? What am I missing?

$mbxs = Get-Content C:\temp\users.txt
foreach ($mbx in $mbxs){
Try{Get-mailbox $mbx| Out-Null
Write-Output "$mbx exists"
} 
Catch [System.exception]
{write-host "$mbx doesnt exist"}
}

when the script comes across a mailbox that cant be found it throws the error on the screen but does not do the write host command.

2
  • 1
    try-catch only works for terminating errors. Likely Get-mailbox is throwing a non-terminating error. You could Get-mailbox $mbx -ErrorAction Stop among other approaches. You could consider just getting all the mailboxes (depending on org size) at once and compare against that list which avoids a bunch of errors. Commented Mar 9, 2018 at 16:20
  • Matt, TY, that did the trick! Commented Mar 9, 2018 at 16:33

1 Answer 1

0

It has to be a terminating error set the variable $erroractionpreference, and ditch the catch definition or be more especific with the exception type.

$mbxs = Get-Content C:\temp\users.txt
$ErrorActionPreference='Stop'
foreach ($mbx in $mbxs){
Try{Get-mailbox $mbx| Out-Null
Write-Output "$mbx exists"
} 
Catch{write-host "$mbx does not exist"}
}

Or if the function is advanced, use the erroractionpreference argument and set it to stop.

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

2 Comments

If you are going to suggest this type of option then you should capture its state before changing it and revert it back when you are done.
That's a good Idea, I generally run all my scripts with 'Stop' as default as I don't want anything that I haven't considered to be executed, but it depends on the case, thanks for the comment Matt.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.