我正在構建一個腳本,該腳本的Try statement與Try
塊和多個Catch
塊。 PowerShell中的This page has provided a good guide to help with identifying error types以及如何在catch
語句中處理它們。可能使用寫入錯誤指定錯誤類型,還是僅使用throw?
到目前爲止,我一直在使用Write-Error
。我認爲可以使用其中一個可選參數(Category
或CategoryTargetType
)來指定錯誤類型,然後使用專門用於該類型的catch
塊。
不幸運:該類型始終列爲Microsoft.PowerShell.Commands.WriteErrorException
。
throw
給了我究竟是什麼。
代碼
[CmdletBinding()]param()
Function Do-Something {
[CmdletBinding()]param()
Write-Error "something happened" -Category InvalidData
}
try{
Write-host "running Do-Something..."
Do-Something -ErrorAction Stop
}catch [System.IO.InvalidDataException]{ # would like to catch write-error here
Write-Host "1 caught"
}catch [Microsoft.PowerShell.Commands.WriteErrorException]{ # it's caught here
Write-host "1 kind of caught"
}catch{
Write-Host "1 not caught properly: $($Error[0].exception.GetType().fullname)"
}
Function Do-SomethingElse {
[CmdletBinding()]param()
throw [System.IO.InvalidDataException] "something else happened"
}
try{
Write-host "`nrunning Do-SomethingElse..."
Do-SomethingElse -ErrorAction Stop
}catch [System.IO.InvalidDataException]{ # caught here, as wanted
Write-Host "2 caught"
}catch{
Write-Host "2 not caught properly: $($Error[0].exception.GetType().fullname)"
}
輸出
running Do-Something...
1 kind of caught
running Do-SomethingElse...
2 caught
我的代碼是做我想要的東西;當throw
完成這項工作時,它不一定是Write-Error
。我想了解的是:
- 是否可以指定與
Write-Error
A型(或以其他方式Write-Error
錯誤區分),使它們可以在不同catch
塊來處理?
N.B.我知道$Error[1] -like "something happen*"
和處理使用if
/else
塊是一個選項。