如何检查 powershell 命令是否成功?

如何检查 powershell 命令是否成功?

是否可以检查 powershell 命令是否成功?

例子:

设置 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,因此我尝试了以下操作:

$测试=设置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"
}

答案1

Set-CASMailbox参考

  • OwaMailboxPolicy范围:

OwaMailboxPolicy参数指定邮箱的 Outlook 网页邮箱策略。您可以使用任何唯一标识 Outlook 网页邮箱策略的值。例如:

  • 姓名
  • 专有名称 (DN)
  • 全局唯一标识符

默认的 Outlook 网页邮箱策略名称为“Default”。

about_CommonParameters可以与任何 cmdlet 一起使用的参数),应用以下任一ErrorVariable方式ErrorAction

ErrorVariable

Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists" -ErrorVariable test
if ($test.Count -neq 0)      ### $test.GetType() is always ArrayList
{
    Write-Host "The Set-CASMailbox command failed: $test"
}
else
{
    Write-Host "The Set-CASMailbox command completed correctly"
}

ErrorAction尝试、捕捉、最终(读关于尝试捕捉 如何使用 Try、Catch 和 Finally 块来处理终止错误):

try {
    Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"  -ErrorAction Stop
                ### set action preference to force terminating error:  ↑↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑
    Write-Host "The Set-CASMailbox command completed correctly"
}  
catch {
    Write-Host "The Set-CASMailbox command failed: $($error[0])"  -ForegroundColor Red
}

无论如何,阅读Write-Host 被认为有害

答案2

除了 JosefZ 的回答之外,自动变量还$Error包含一个错误数组,因此您可以查看 $Error.Count 属性以查看它是否上升。我认为-ErrorVariable这是最好的答案。Get-Help about_AutomaticVariables详情请参阅。

相关内容