Exchange

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

  • August 25, 2021

是否可以檢查 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範圍:

OwaMailboxPolicy參數指定郵箱的 Outlook on web 郵箱策略。您可以使用唯一標識 Web 郵箱策略上的 Outlook 的任何值。例如:

  • 姓名
  • 專有名稱 (DN)
  • 圖形使用者界面

Web 郵箱策略上的預設 Outlook 的名稱是 Default。

閱讀about_CommonParameters可與任何 cmdlet 一起使用的參數),應用ErrorVariableErrorAction

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"
}

ErrorActionTry,Catch,Finally(閱讀about_Try_Catch_Finally 如何使用 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 Considered Harmful**。

引用自:https://serverfault.com/questions/862092