David
David

Reputation: 81

Try Catch/Exception for ManagementObjectNotFoundException and ActiveDirectory/Outlook

This might be a pretty basic question, but i haven't seen it on the forms. Bear with me i'm new to powershell

I'm trying to catch this exception(ManagementObjectNotFoundException) when a username is not found in our Active Directory Database.

Set-ExecutionPolicy RemoteSigned
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
$user2 = Read-Host 'Enter account name of the user who is being added'
try {
$user = Read-Host 'Enter account name of the users email you wish to have access to'
Add-MailboxPermission –Identity $user -User $user2 -AccessRights FullAccess –InheritanceType All –Automapping $false
}
catch [ManagementObjectNotFoundException] {
    "User not found, try again"
     $user = Read-Host 'Enter account name of the users email you wish to have access to - Test'
}
Remove-PSSession $Session

I've also tried this option:

catch {
  Write-Host "An error occurred:"
  Write-Host $_
}

and I still receive this error:

The operation couldn't be performed because object 'test1' couldn't be found on 'BN4PR12A003DC03.NAMPR12A003.PROD.OUTLOOK.COM'.
    + CategoryInfo          : NotSpecified: (:) [Add-MailboxPermission], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=BYAPR12MB2885,RequestId=25cd1eb7-055e-4250-bd43-6d2f5d528f12,TimeStamp=11/12/2019 9:38:16 PM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] C5EDB577,Microsoft.Exchange.Management.RecipientTasks.AddMailboxP 
   ermission
    + PSComputerName        : outlook.office365.com

Upvotes: 2

Views: 3332

Answers (1)

codewario
codewario

Reputation: 21468

You need to throw what's called a terminating error in order to catch exceptions. You can set the error action preference at your script level:

$ErrorActionPreference = "Stop"

or add -ErrorAction Stop to any cmdlets you want to catch errors from. Errors can't be caught if the exception is non-terminating. By default, errors are set to Continue but can be changed in one of the ways below:

Error Action Preferences

  • Continue: Displays the error but continues with execution. This is the default.
  • SilentlyContinue: Hides the error and continues with execution.
    • Error is suppressed but is still added to the $Error collection.
  • Stop: Throws a terminating error. The error action must be set to Stop to catch exceptions.
  • Inquire: Asks the user what to do.
  • Suspend: Used with Powershell Workflows. Suspends a Workflow job so it can be resumed later.
  • Ignore: Similar to SilentlyContinue, it suppresses the error and continues executing. Can only be set with the -ErrorAction parameter, Ignore cannot be set to $ErrorActionPreference.
    • Unlike SilentlyContinue, Ignore will omit adding the error to the $Error collection.

A Note About Terminating errors

Note that terminating errors cannot be converted to non-terminating in the same way we can treat non-terminating errors as terminating. In other words, most exceptions originating from the framework or exceptions thrown from PowerShell with the throw statement must be handled via try/catch/finally blocks. Neither $ErrorActionPreference or -ErrorAction has any bearing on how the exception is handled.

As this restriction includes Ignore and SilentlyContinue, you cannot suppress or ignore terminating errors with these preference values. You must handle them to prevent script termination.

Upvotes: 5

Related Questions