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

14
我想要访问与Powershell打印的错误记录相同的消息。
示例:
这是异常消息,位于C:\Documents and Settings\BillBillington\Desktop\psTest\exThrower.ps1:1字符:6
throw <<<< (New-Object ArgumentException("This is the exception")); CategoryInfo : OperationStopped: (:) [], ArgumentException FullyQualifiedErrorId : This is the exception
当我通过$Error[0]获取最后一个ErrorRecord时,似乎无法简单地获取这些信息。
我在社区扩展中找到了一个名为'Resolve-Error'的函数here,它大致符合我的需求,但会打印出一大堆我不需要的半格式化列表,我还需要将其剥离。
有没有办法访问Powershell使用的消息,或者如果失败的话,有没有更简单的方法来获取我关心的值的哈希,以便我可以按照自己选择的格式将它们放入字符串中?
5个回答

24
怎么样:
$x = ($error[0] | out-string)

那是你想要的吗?


18
如果你想要一条比@tomasr提供的略短的消息(有时更加用户友好?),那么这样做就可以:
$error[0].ToString() + $error[0].InvocationInfo.PositionMessage

你将会得到类似于:

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

这些技术信息将被排除:

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

6

我将其进一步扩展,因为我不喜欢来自$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

您可以通过查看其他内容来构建自己的字符串,方法如下:
$Error | Get-Member
$Error[0].InvocationInfo | Get-Member

0

类似于@tomasr,但更短:

$($error[0])

对于脚本中的所有错误:

$($error)

0
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
}

你也可以这样做,就能获取有关错误的所有信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接