为ManagementObjectNotFoundException和ActiveDirectory / Outlook尝试Catch / Exception

时间:2019-11-12 21:46:29

标签: powershell

这可能是一个非常基本的问题,但是我没有在表格上看到它。忍受我,我是PowerShell的新手

当我们在Active Directory数据库中找不到用户名时,我正在尝试捕获此异常(ManagementObjectNotFoundException)。

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

我也尝试过此选项:

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

我仍然收到此错误:

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

1 个答案:

答案 0 :(得分:3)

您需要引发终止错误,以捕获异常。您可以在脚本级别设置错误action preference

$ErrorActionPreference = "Stop"

或将-ErrorAction Stop添加到要捕获错误的任何cmdlet中。如果异常是非终止的,则无法捕获错误。默认情况下,错误设置为Continue,但可以通过以上方式之一进行更改:

错误操作偏好设置

  • 继续:显示错误,但继续执行。这是默认设置。
  • SilentlyContinue (SilentlyContinue):隐藏错误并继续执行。
  • 停止:引发终止错误。错误操作必须设置为Stop才能捕获异常。
  • 查询:询问用户该怎么做。
  • 挂起:与Powershell工作流一起使用。暂停工作流作业,以便以后可以恢复。
  • 忽略:类似于SilentlyContinue,它可以抑制错误并继续执行。只能使用-ErrorAction参数设置,Ignore不能设置为$ErrorActionPreference