我正在构建一个脚本,该脚本的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
块是一个选项。