Powershell抛出数据异常

Dav*_* Wu 3 powershell exception throw

如何在PowerShell中使用'throw'方向来抛出自定义数据对象的异常?说,它能做到吗?:

throw 'foo', $myData
Run Code Online (Sandbox Code Playgroud)

那么数据可以用在'catch'逻辑中:

catch {
    if ($_.exception.some_property -eq 'foo') {
        $data = $_.exception.some_field_to_get_data
        # dealing with data
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:
我的目的是知道是否有一个简短而酷的语法来抛出异常(没有显式创建我自己的类型),其名称我可以通过其名称来决定并在'catch'块中处理它的数据.

Mat*_*sen 5

你可以使用throw任何类型的System.Exception实例(这里使用一个XamlException例子):

try {
    $Exception = New-Object System.Xaml.XamlException -ArgumentList ("Bad XAML!", $null, 10, 2)
    throw $Exception
}
catch{
    if($_.Exception.LineNumber -eq 10){
        Write-Host "Error on line 10, position $($_.Exception.LinePosition)"
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您运行的是5.0或更高版本的PowerShell,则可以使用新的PowerShell类功能来定义自定义异常类型:

class MyException : System.Exception
{
    [string]$AnotherMessage
    [int]$SomeNumber

    MyException($Message,$AnotherMessage,$SomeNumber) : base($Message){
        $this.AnotherMessage = $AnotherMessage
        $this.SomeNumber     = $SomeNumber
    }
}

try{
    throw [MyException]::new('Fail!','Something terrible happened',135)
}
catch [MyException] {
    $e = $_.Exception
    if($e.AnotherMessage -eq 'Something terrible happened'){
        Write-Warning "$($e.SomeNumber) terrible things happened"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @4c74356b41 查看 MSDN 上的构造函数文档(上面链接),或者查看重载定义:`[System.Xaml.XamlException]::new` (v 5.0+) 或 `[System.Xaml.XamlException].GetConstructors ()|%{'new {0}({1})'-f$_.DeclaringType,(($_.GetParameters()|%{'{0} {1}'-f$_.ParameterType.FullName ,$_.Name})-join', ')}`(旧版本) (2认同)