user3066571
user3066571

Reputation: 1471

How to prevent ManagementObjectNotFoundException from printing

I'm trying to test out a script that creates exchange mailboxes for existing users. At the end I want to have a little piece that tests and informs the user whether or not it was successful. What I have is below.

$mail = Get-Mailbox [email protected]

$checkmail = @($mail).count

if($checkmail -eq 0)
{
write-host "Does not exist"
}
else
{
write-host "exists"
}

This actually works just fine, but when the object doesn't exist, it also spits out a huge Powershell error to boot. I just don't want that part to be there. I've tried a try/catch block on the whole thing, and it for some reason just ignored it. The error is as follows:

Get-Mailbox : The operation could not be performed because object '[email protected]' could not
be found on the domain controller 'domainnamehere'
+ $mail = Get-Mailbox [email protected]
+          ~~~~~~~~~~~~~~~~~~
    + CategoryInfo            : InvalidData: (:) [Get-Mailbox], ManagementObjectNotFoundException
    + FullyQualifiedErrorID   : 3AAE54AC,Microsoft.Exchange.Management.RecipientTasks.Getmailbox

Any help would be appreciated.

Upvotes: 1

Views: 4836

Answers (1)

Matt
Matt

Reputation: 46720

One thing you could do is set the -ErrorAction for Get-Mailbox

$mailbox = Get-Mailbox [email protected] -ErrorAction SilentlyContinue

The error for that command will be surpressed from the console ( but still occur ). You will have to check the value of $mailbox in case it is empty with a simple If.

If($mailbox){
    Write-Host "Good mailbox"
} Else {
    Write-Host "Bad mailbox"
} 

The try block might not have worked if the error was non-terminating. If you have a try block setting -ErrorAction Stop might have made that work as well.

Upvotes: 1

Related Questions