2017-10-06 78 views
1

考慮這個簡單的代碼:錯誤行爲不停止腳本

Read-Host $path 
try { 
    Get-ChildItem $Path -ErrorAction Continue 
} 

Catch { 
    Write-Error "Path does not exist: $path" -ErrorAction Stop 
    Throw 
} 

Write-Output "Testing" 

爲什麼是「測試」如果指定了無效的路徑將被打印到的殼呢?

腳本不停止在catch塊中。我究竟做錯了什麼?

回答

0

我認爲這是你需要的:

$path = Read-Host 'Enter a path' 

try { 
    Get-ChildItem $Path -ErrorAction Stop 
} 
Catch { 
    Throw "Path does not exist: $path" 
} 

Write-Output "Testing" 

根據Sage的回答,您需要在Try塊中更改爲-ErrorAction Stop。這會強制Get-ChildItem cmdlet發出終止錯誤,然後觸發Catch塊。默認情況下(和Continue ErrorAction選項)它會拋出一個無法終止的錯誤,這些錯誤不會被try..catch捕獲。

如果您希望您的代碼在Catch塊中停止,請使用Throw和您要返回的消息。這將產生一個終止錯誤並停止腳本(Write-Error -ErrorAction Stop也將實現終止錯誤,這只是一個更復雜的方法。通常,當您要返回非終止錯誤消息時,您應該使用Write-Error)。

1

在您的Try Catch塊中,您需要設置Get-ChildItem -ErrorAction Stop ,以便在Catch塊中捕獲異常。

隨着繼續,您指示命令不會在發生實際錯誤時產生終止錯誤。

編輯: 此外,您的throw語句在那裏沒有用處,您無需爲寫入錯誤指定錯誤操作。

這是修改後的代碼。

$path = Read-Host 

try { 
    Get-ChildItem $Path -ErrorAction stop 
} 

Catch { 
    Write-Error "Path does not exist: $path" 
} 

附加說明

你可以通過設置默認操作應用此默認行爲(如果這是你想要的)在整個腳本停止使用:

$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop