是否可以检查 powershell 命令是否成功?
例子:
Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"
导致错误:
Outlook Web App mailbox policy "DoNotExists" wasn't found. Make sure you typed the policy name correctly.
+ CategoryInfo : NotSpecified: (0:Int32) [Set-CASMailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : 9C5D12D1,Microsoft.Exchange.Management.RecipientTasks.SetCASMailbox
我认为应该可以获取FullyQualifiedErrorId,所以我尝试了以下方法:
$test = Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"
但看起来错误没有转移到测试变量中。
那么这里执行以下操作的正确方法是什么:
$test = Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"
if ($test -eq "error")
{
Write-Host "The Set-CASMailbox command failed"
}
else
{
Write-Host "The Set-CASMailbox command completed correctly"
}
阅读
Set-CASMailbox
参考:OwaMailboxPolicy
范围:Set-CASMailbox
情况)。阅读about_CommonParameters(可与任何 cmdlet 一起使用的参数),应用
ErrorVariable
或ErrorAction
:ErrorVariable
:ErrorAction
和Try,Catch,Finally(阅读about_Try_Catch_Finally 如何使用 Try、Catch 和 finally 块来处理终止错误):无论如何,请阅读Write-Host Considered Harmful。
除了 JosefZ 的回答之外,自动变量
$Error
还包含一系列错误,因此您可以查看 $Error.Count 属性以查看它是否上升。我认为-ErrorVariable
虽然是最好的答案。详情见Get-Help about_AutomaticVariables
。