Powershell 可以使用Write error指定错误类型,或仅使用throw指定错误类型?

Powershell 可以使用Write error指定错误类型,或仅使用throw指定错误类型?,powershell,error-handling,try-catch,powershell-5.0,Powershell,Error Handling,Try Catch,Powershell 5.0,我正在构建一个脚本,其中包含一个包含Try块和多个Catch块的脚本。以及如何在catch语句中处理它们 到现在为止我一直在用。我认为其中一个可选参数(Category或CategoryTargetType)可以用来指定错误类型,然后是专门用于该类型的catch块 运气不佳:类型始终列为Microsoft.PowerShell.Commands.WriteErrorException throw给了我想要的东西 代码 [CmdletBinding()]param() Function Do-S

我正在构建一个脚本,其中包含一个包含
Try
块和多个
Catch
块的脚本。以及如何在
catch
语句中处理它们

到现在为止我一直在用。我认为其中一个可选参数(
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
执行作业时,它不一定是
写入错误
。我想了解的是:

  • 是否可以指定具有
    写入错误
    (或以其他方式区分
    写入错误
    错误)的类型,以便可以在不同的
    捕获
    块中处理它们
注意:我知道
$Error[1]——比如“发生了什么事*”
,如果
/
其他
块是一个选项,则使用
进行处理


您可以使用-Exception参数指定从写入错误引发的异常类型,请参见下面的示例(PS5)或Get-Help Write Error的示例4:


您可以使用-Exception参数指定要从写入错误引发的异常类型,请参见下面的示例(PS5)或Get-Help Write Error的示例4:

try { 
    Write-Error -ErrorAction Stop -Exception ([System.OutOfMemoryException]::new())  } 
catch [System.OutOfMemoryException] { 
    "Just system.OutOfMemoryException"
} catch {
    "Other exceptions"
}