Exchange
如何檢查powershell命令是否成功?
是否可以檢查 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" }
OwaMailboxPolicy
範圍:該
OwaMailboxPolicy
參數指定郵箱的 Outlook on web 郵箱策略。您可以使用唯一標識 Web 郵箱策略上的 Outlook 的任何值。例如:
- 姓名
- 專有名稱 (DN)
- 圖形使用者界面
Web 郵箱策略上的預設 Outlook 的名稱是 Default。
- Cmdlet 輸入和輸出類型。如果輸出類型欄位為空,則 cmdlet 不返回數據(就是這種
Set-CASMailbox
情況)。閱讀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(閱讀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**。