Categories
Development

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

Leave a Reply

Your email address will not be published. Required fields are marked *