【问题标题】:Possible to specify error Type using Write-Error, or only with throw?可以使用 Write-Error 或仅使用 throw 指定错误类型?
【发布时间】:2017-11-25 13:05:30
【问题描述】:

我正在构建一个脚本,它将有一个 Try statementTry 块和多个 Catch 块。 PowerShell 中的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。我想了解的是:

  • 是否可以指定带有Write-Error 的类型(或以其他方式区分Write-Error 错误),以便它们可以在不同的catch 块中处理?

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

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

【问题讨论】:

    标签: powershell error-handling try-catch powershell-5.0


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 2015-07-05
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      相关资源
      最近更新 更多