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.

  • 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. – Matt Mar 09 '18 at 16:20
  • Matt, TY, that did the trick! – user2600700 Mar 09 '18 at 16:33

1 Answers1

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.

Roque Sosa
  • 573
  • 4
  • 21
  • 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. – Matt Mar 09 '18 at 16:37
  • 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. – Roque Sosa Mar 09 '18 at 16:43