How can I get powershell exception descriptions into a string?

后端 未结 5 1529
猫巷女王i
猫巷女王i 2021-01-04 09:15

I want to have access to the same message that Powershell prints when you send an error record to the output stream

Example:

This is the excep

5条回答
  •  無奈伤痛
    2021-01-04 10:05

    I took it a bit further because I didn't like the multilines from $error[0].InvocationInfo.PositionMessage.

    Function FriendlyErrorString ($thisError) {
        [string] $Return = $thisError.Exception
        $Return += "`r`n"
        $Return += "At line:" + $thisError.InvocationInfo.ScriptLineNumber
        $Return += " char:" + $thisError.InvocationInfo.OffsetInLine
        $Return += " For: " + $thisError.InvocationInfo.Line
        Return $Return
    }
    
    [string] $ErrorString = FriendlyErrorString $Error[0]
    $ErrorString
    

    You can look at what else is availible to construct your own String via:

    $Error | Get-Member
    $Error[0].InvocationInfo | Get-Member
    

提交回复
热议问题