2015-04-02 63 views
5

有點像perl中的<statement> || die,這個東西很簡潔,我可以把它放在每個關鍵語句中,以避免在腳本的其他部分出錯時打擾powershell。在PowerShell中是否存在「... || die」等價物?

+1

usualy,在$ ErrorPreferenceVariable被設置爲 '停止' 和一個try/catch結構來處理錯誤 – 2015-04-02 11:19:17

回答

5

大多數命令都支持-ErrorAction通用參數。指定-ErrorAction Stop通常會在發生錯誤時暫停腳本。見Get-Help about_CommonParameters

默認情況下,-ErrorActionContinue。您可以通過更改$ErrorActionPreference的值來更改默認選項。見Get-Help about_Preference_Variables

如果詳細程度確實是一個問題,-ErrorAction別名爲-ea

+0

當時這對我有用,非常感謝! – 2018-01-22 09:38:26

1

另一種在PowerShell中實現類似...|| die的構造的方法,無需添加巨大的try-catch構造,可以使用自動變量$?
Get-Help about_Automatic_variables

$? 
    Contains the execution status of the last operation. It contains 
    TRUE if the last operation succeeded and FALSE if it failed. 

只需添加下面的右各關鍵語句後:

if(-not $?){ 
    # Call Write-EventLog or write $Error[0] to an xml or txt file if you like 
    Exit(1) 
} 
+0

謝謝Mathaias! – 2018-01-22 09:38:00

+0

@Lyt_Seeker非常歡迎^ _ ^請點擊左邊的複選標記,考慮標記我的答案「accepted」 – 2018-01-22 11:38:00

+0

那時候,培根比特這樣的解決方案爲我工作; 我已經使用$?後來換了其他的東西,但他的回答爲我解決了。感謝您在這裏再次輸入! – 2018-01-22 13:36:37

相關問題