2014-09-29 42 views
1

我正在編寫的腳本經常嘗試刪除它沒有能力的文件。這會引發一些錯誤,一個是沒有足夠訪問權限的錯誤,另一個是稍後嘗試刪除包含第一個問題的非空文件夾的錯誤。這些東西很好,但我仍然想輸出錯誤消息,如果有任何東西被拋出,那不是這兩條消息之一。Powershell錯誤等價於try-catch嗎?

try-catch塊沒有捕捉任何東西,因爲它們是錯誤而不是異常。

try 
{ 
    Remove-Item D:\backup\* -Recurse 
    Write-Host "Success" -ForegroundColor Green 
    Write-Host $error.count 
} 
catch 
{ 
    Write-Host "caught!" -ForegroundColor Cyan 
} 

即使$error.count裏面有錯誤,它仍然成功地完成了try-block。我是不是每次都要手動檢查$ error是否有新內容,還是有更好的方法來做這件事?謝謝!

回答

2

在Try/Catch中,僅在終止錯誤時調用Catch塊。

使用ErrorAction通用參數來強制所有的錯誤被終止:

try 
{ 
    Remove-Item D:\backup\* -Recurse -ErrorAction Stop 
    Write-Host "Success" -ForegroundColor Green 
    Write-Host $error.count 
} 
catch 
{ 
    Write-Host "caught!" -ForegroundColor Cyan 
} 
0

或者使用全局erroraction:

try { 
$erroractionpreference = 'stop' 
Remove-Item D:\backup\* -Recurse 
Write-Host "Success" -ForegroundColor Green 
Write-Host $error.count 
} catch { 
Write-Host "caught!" -ForegroundColor Cyan 
}