2010-08-04 80 views
10

我想有机会获得PowerShell将打印当您发送错误记录到输出流相同的消息如何将powershell异常描述转换为字符串?

例子:

这是异常消息在 C:\ Documents和 设置\ BillBillington \桌面\ psTest \ exThrower.ps1:1 炭:6 +扔< < < <(新物体的ArgumentException( “这是 异常”)); + CategoryInfo:OperationStopped:(:) [], ArgumentException的 + FullyQualifiedErrorId:这是例外

时做$错误得到最后ErrorRecord [0]我我似乎无法弄清楚如何让一个简单的方法

我发现这个“解决错误”功能从社区扩展here这确实大概我想这是什么信息,但它打印的东西,我并不需要一个巨大的半格式化列表我必须去掉

有没有accessi的方法如果Powershell使用的消息或未能通过简单的方式获取我关心的值的散列,那么我可以将它们放入我选择的格式的字符串中?

回答

13

如果你想要一个有点短消息(有时对用户更友好?)不是@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 
13

如何:

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

这是你想要的吗?

+0

1 +谢谢,谢谢 – Willbill 2010-08-04 13:13:45

4

我花了一点时间,因为我不喜欢多线f rom $ 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
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 
} 

你也可以做到这一点,你会得到所有信息有关错误

相关问题