2017-08-28 94 views
1

我目前正在運行一個腳本,我可以在控制面板中看到異常。 例如Powershell創建日誌文件例外

Exception calling "ExecuteNonQuery" with "0" argument(s): "Cannot drop the table 'testtabel', because it does not exist or you do not have permission." 
At line:383 char:36 
+   $insertData.ExecuteNonQuery <<<<() 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : DotNetMethodException 

這是腳本中沒有錯誤,以使腳本繼續前進,但我想保存這些例外的文本文件。我嘗試了不同的方法,如

$_ | Out-File C:\errors.txt -Append 

或我在互聯網上找到的其他日誌功能。

只有一種簡單的方法可以將這些異常提取到文本文件中嗎?

+0

'$ error'是錯誤的自動變量。所以如果你想導出最後一個錯誤,它會是'$ error [0] | Out-File C:\ errors.txt -Append' – BenH

+0

您是否從管道中嘗試捕獲$ _? – ArcSet

回答

0

有兩種方法,即在存儲它的所有錯誤對象$Error自動變量,或Try{}Catch{}使用$PSItem$_自動變量。

Try { 
    .. commands .. 
} Catch { 
    # Error TYPE 
    "[$($_.Exception.GetType().FullName)]" | Out-File C:\Temp\errorlog.txt 
    # Error MESSAGE 
    $_.Exception.Message | Out-File C:\Temp\errorlog.txt 
}