如何将powershell异常描述转换为字符串?

Wil*_*ill 10 powershell exception

我希望能够访问Powershell在向输出流发送错误记录时打印的相同消息

例:

这是异常消息在C:\ Documents and Settings\BillBillington\Desktop\psTest\exThrower.ps1:1 char:6 + throw <<<<(New-Object ArgumentException("This is the exception")); + CategoryInfo:OperationStopped:(:) [],ArgumentException + FullyQualifiedErrorId:这是例外

我通过执行$ Error [0]来获取最后一个ErrorRecord我似乎无法弄清楚如何以简单的方式获取此信息

我发现这个"解决错误"功能从社区扩展这里该不会是我想大概什么,但它打印的东西,一个巨大的半格式化列表我不需要,我必须再带

有没有办法访问Powershell使用或失败的消息,这是一种更简单的方法来获取我关心的值的哈希值,所以我可以将它们放入我选择的格式的字符串中?

tom*_*asr 18

怎么样:

$x = ($error[0] | out-string)
Run Code Online (Sandbox Code Playgroud)

那是你想要的吗?


Rom*_*min 15

如果你想要一个更短的消息(有时候用户更友好?)比@tomasr建议这样做:

$error[0].ToString() + $error[0].InvocationInfo.PositionMessage
Run Code Online (Sandbox Code Playgroud)

你会得到类似的东西:

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
Run Code Online (Sandbox Code Playgroud)

此技术信息将被排除在外:

+ CategoryInfo          : ObjectNotFound: (C:\TEMP\_100804_135716\missing:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Run Code Online (Sandbox Code Playgroud)


小智 6

我更进一步,因为我不喜欢 $error[0].InspirationInfo.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
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式查看还有什么可用于构造您自己的字符串:

$Error | Get-Member
$Error[0].InvocationInfo | Get-Member
Run Code Online (Sandbox Code Playgroud)