【问题标题】:Display entire error message from logfile using powershell使用 powershell 显示来自日志文件的整个错误消息
【发布时间】:2020-09-17 17:03:15
【问题描述】:

其中一个批处理脚本会创建一个日志文件,它可能会出现如下错误消息

Msg 2714, Level 16, State 1:
Server 'ABC', Procedure 'proc_test1', Line 189:
There is already an object named 'table_test' in the database.
Msg 207, Level 16, State 4:
Server 'ABC', Procedure 'proc_test2', Line 197:
Invalid column name 'employee'.
Msg 207, Level 16, State 4:
Server 'ABC', Procedure 'proc_test2', Line 197:
Invalid column name 'address'.

使用 powershell 脚本从日志文件中读取错误并将其报告给邮件。我正在使用它,它也排除了某些警告消息。

Select-String -Path 'C:\Users\BatchLog_20200911.txt' -Pattern "Msg","Error" | Select-String -Pattern "SQLState = S1000, NativeError = 0" -notmatch | select-object -Property Line,LineNumber

输出如下

Line                                                                                                                LineNumber
----                                                                                                                ----------
Msg 2714, Level 16, State 1:                                                                                              2791
Msg 207, Level 16, State 4:                                                                                               2794
Msg 207, Level 16, State 4:                                                                                               2797
CT-LIBRARY error:                                                                                                         2828
    ct_results(): network packet layer: internal net library error: Net-Library operation terminated due to disconnect       2829
"Errors encountered during execution.  Exited with status: 596"                                                           4168

所以,它只打印与查询匹配的行。我想打印具有实际错误消息描述的下一行。任何建议在这里。谢谢。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    使用Select-String cmdlet 的-Context 参数:

    Select-String -Path 'C:\Users\BatchLog_20200911.txt' "Msg","Error" -Context 0,1 | 
      ForEach-Object { 
        if ($_.Context.PostContext[0] -notmatch 'SQLState = S1000, NativeError = 0') {
          [pscustomobject] @{
            Line = $_.Context.PostContext[0]
            LineNumber = $_.LineNumber
          }
        }
      }
    
    • -Context 0,1 捕获 0before1after 以及实际匹配的行。

    • 在生成的Microsoft.PowerShell.Commands.MatchInfo 实例中,.Context.PostContext[0] 提供对第一个上下文后(后)行的访问。

    使用您的示例输入,上述结果:

    Line                                            LineNumber
    ----                                            ----------
    Server 'ABC', Procedure 'proc_test1', Line 189:          1
    Server 'ABC', Procedure 'proc_test2', Line 197:          4
    Server 'ABC', Procedure 'proc_test2', Line 197:          7
    

    【讨论】:

    • 感谢您的帮助@mklement0
    • 很高兴听到它有帮助,@Kris。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2015-06-25
    相关资源
    最近更新 更多