这可能是一个非常基本的问题,但是我没有在表格上看到它。忍受我,我是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
答案 0 :(得分:3)
您需要引发终止错误,以捕获异常。您可以在脚本级别设置错误action preference:
$ErrorActionPreference = "Stop"
或将-ErrorAction Stop
添加到要捕获错误的任何cmdlet中。如果异常是非终止的,则无法捕获错误。默认情况下,错误设置为Continue
,但可以通过以上方式之一进行更改:
Stop
才能捕获异常。SilentlyContinue
,它可以抑制错误并继续执行。只能使用-ErrorAction
参数设置,Ignore
不能设置为$ErrorActionPreference
。