How can I get powershell exception descriptions into a string?

后端 未结 5 1509
猫巷女王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 09:47

    Similar to @tomasr, but shorter:

    $($error[0])
    

    For all errors in a script:

    $($error)
    
    0 讨论(0)
  • 2021-01-04 09:53

    How about:

    $x = ($error[0] | out-string)
    

    Is that what you wanted?

    0 讨论(0)
  • 2021-01-04 10:05

    If you want a bit shorter message (more user friendly sometimes?) than @tomasr suggests this will do:

    $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
    

    You will get something like:

    Cannot find path 'C:\TEMP\_100804_135716\missing' because it does not exist.
    At C:\TEMP\_100804_135716\test.ps1:5 char:15
    +   Get-ChildItem <<<<  missing
    

    This technical info will be excluded:

    + CategoryInfo          : ObjectNotFound: (C:\TEMP\_100804_135716\missing:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-04 10:10
    Foreach ($Errors in $Error){
      #Log Eintrag wird zusammengesetzt und in errorlog.txt geschrieben
      "[$Date] $($Errors.CategoryInfo.Category) $($Errors.CategoryInfo.Activity) $($Errors.CategoryInfo.Reason) $($Errors.CategoryInfo.TargetName) $($Errors.CategoryInfo.TargetType) $($Errors.Exception.Message)" |Add-Content $Path\errorlog.txt -Encoding UTF8
    }
    

    You can also do this and you will get all Informations about the Error

    0 讨论(0)
提交回复
热议问题