如何“捕捉”一个失败的命令,不能使用try … catch?

我正在运行以下脚本,对于不存在的邮箱失败

Set-MailboxDatabase rdb16 -AllowFileRestore:$true Mount-Database rdb16 $stats = Get-MailboxStatistics -Database rdb16 ForEach ($item in $stats) { try { get-mailbox -Identity $item.DisplayName | Set-Mailbox -Database rdb16 -Force } catch{ write-host "Create Mailbox:" } } 

这是失败

 The operation couldn't be performed because object 'schmoe, joe' couldn't be found on 'NYCEXRESTOREDC0.sss.com'. + CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException + FullyQualifiedErrorId : CEA5387A,Microsoft.Exchange.Management.RecipientTasks.GetMailbox 

如何正确检测上面显示的错误,因为它实际上并没有提供我期望在C#世界中出现的“exception”风格错误

您看到此行为,因为try / catch块仅适用于终止错误( MSDN Powershell错误types参考 )

您可以通过更改$ ErrorActionPreferencevariables来操作Powershell的工作方式。

如果你调整你的脚本在上面有$ErrorActionPreference = "Stop" ,那么所有的错误将被认为是终止错误,try / catch块将起作用。

如果您只想为一个命令更改错误操作,则可以使用-ErrorAction参数为该命令进行更改。

如果你想“捕捉”一个错误,我会告诉你我的例子,也许你可以build立它。

 function LoggedOnUser($MachineNameOrIP){ $LoggedOnUser = "CouldNotGetUser" trap [Exception]{ # this installs an error handler for the function Write-Host "Error Accessing WMI - $MachineNameOrIP" Log("Error Accessing WMI - $MachineNameOrIP") continue; } $LoggedOnUser = Get-WMIObject Win32_Process -filter 'name="explorer.exe"' -computername $MachineNameOrIP | ForEach-Object { $owner = $_.GetOwner(); '{0}\{1}' -f $owner.Domain, $owner.User } | Sort-Object | Get-Unique return $LoggedOnUser 

}

正如您可能猜到的那样,这是查找机器的login用户的function。 中间有一部分是为了捕捉任何exception。 你可能能够逃脱

 trap [ManagementObjectNotFoundException] {....} 

由于powershell紧密联系在一起。