gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:34:48 24 4
gpt4 key购买 nike

我正在构建一个脚本,该脚本将具有带有Try块和多个Catch块的Try statement。 PowerShell中的This page has provided a good guide to help with identifying error types,以及如何在catch语句中处理它们。

到目前为止,我一直在使用 Write-Error 。我认为可以使用一个可选参数(CategoryCategoryTargetType)来指定错误类型,然后使用一个专门用于该类型的catch块。

不走运:该类型始终列为Microsoft.PowerShell.Commands.WriteErrorExceptionthrow给了我确切的追求。

代码

[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块进行处理是一种选择。

    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"
    }

    关于powershell - 可以使用Write-Error或仅使用throw指定错误类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696220/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com