这可能是一个非常基本的问题,但我还没有在表格上看到它。请耐心等待,我是 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
你需要抛出所谓的终止错误以捕获异常。您可以设置错误行动偏好在您的脚本级别:
$ErrorActionPreference = "Stop"
or add -ErrorAction Stop
到您想要从中捕获错误的任何 cmdlet。如果异常未终止,则无法捕获错误。默认情况下,错误设置为Continue
但可以通过以下方式之一进行更改:
错误操作首选项
-
Continue:显示错误但继续执行。这是默认设置。
-
SilentlyContinue: Hides the error and continues with execution.
-
Stop:抛出终止错误。错误操作必须设置为
Stop
捕获异常。
-
Inquire:询问用户要做什么。
-
Suspend:与 Powershell 工作流程一起使用。暂停工作流作业以便稍后可以恢复。
-
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
将省略将错误添加到$Error
收藏。
关于终止错误的注意事项
注意终止错误无法转换为非终止同样,我们可以将非终止错误视为终止错误。换句话说,大多数异常源自框架或从 PowerShell 抛出的异常throw
声明必须通过处理try
/catch
/finally
块。两者都不$ErrorActionPreference
or -ErrorAction
与如何处理异常有任何关系。
由于此限制包括Ignore
and SilentlyContinue
, 您无法使用这些首选项值抑制或忽略终止错误. You must处理它们以防止脚本终止。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)