2017-08-28 86 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 
}