我正在构建一个脚本,其中包含Try statement Try
块和多个Catch
块。 PowerShell中的This page has provided a good guide to help with identifying error types,以及如何在catch
语句中处理它们。
到目前为止,我一直在使用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
我的代码正在做我想要的事情;当Write-Error
完成工作时,它不必是throw
。我想了解的是:
Write-Error
指定类型(或以其他方式区分Write-Error
错误),以便可以在不同的 catch
块? <子> N.B。我知道$Error[1] -like "something happen*"
并使用if
/ else
块处理是一种选择。
答案 0 :(得分:4)
您可以使用-Exception参数指定要从Write-Error中抛出的异常类型,请参阅下面的示例(PS5)或Get-Help Write-Error的示例4: https://msdn.microsoft.com/powershell/reference/5.1/microsoft.powershell.utility/Write-Error
try {
Write-Error -ErrorAction Stop -Exception ([System.OutOfMemoryException]::new()) }
catch [System.OutOfMemoryException] {
"Just system.OutOfMemoryException"
} catch {
"Other exceptions"
}