2010-08-04 75 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 
} 

你也可以做到這一點,你會得到所有信息有關錯誤

相關問題