可以使用 Write-Error 或仅使用 throw 来指定错误类型吗?

Possible to specify error Type using Write-Error, or only with throw?

我正在构建一个脚本,它将在 PowerShell 中包含 Try statement with Try block and multiple Catch blocks. This page has provided a good guide to help with identifying error types,以及如何在 catch 语句中处理它们。

到目前为止,我一直在使用 Write-Error。我认为可选参数之一(CategoryCategoryTargetType)可用于指定错误类型,然后是专门用于该类型的 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。我想了解的是:

N.B。我知道 $Error[1] -like "something happen*" 和处理使用 if/else 块是一个选项。

Closest related question I could find on SO - Write-Error v throw in terminating/non-terminating context

您可以使用-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"
}