首页 > 解决方案 > 使用 Powershell 查找模式

问题描述

我有一个日志文件,其中包含来自多个日志文件的多行文本。我正在尝试使用 Send-MailMessage 在电子邮件正文中发送日志文件内容。

Exception我的问题是:我正在尝试从多个日志文件中提取一串文本。我想在 if 语句中匹配这个。我试过像下面这样的脚本,但没有运气。任何见解将不胜感激。

日志文件内容:

25/Dec/2018 11:50:05.224 ERROR  3805     com.crm.dao.CrmDaoJdbcImpl(L:608) - Exception created
Rerun the transaction.
               at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
               at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1522)
               at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
               at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
               at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)

提取所需输出后:

25/Dec/2018 11:50:05.224 ERROR  3805     com.crm.dao.CrmDaoJdbcImpl(L:608) - Exception created

这是脚本的片段以供参考。

$SourceDir = "C:\Temp\TEMP2"
#$GCI_Fiter = '*.txt'
$Include=@("*.log","*.txt")

$FileList = Get-ChildItem -LiteralPath $SourceDir -Include "$Include" -File

foreach ($FL_Item in $FileList)   {
$FLI_Content = Get-Content -LiteralPath $FL_Item.FullName -Raw

if ( ???????? )  {
$ExceptionLines = $FLI_Content | Select-String -SimpleMatch 'Exception' | ForEach-Object {$_.ToString().Trim()}

$ExceptionLines
}

else {
Write-Warning "Could not find Exception keyword from '$FL_Item.FullName'.."
}


}

提前致谢,

标签: regexpowershell

解决方案


查找所有包含单词“Exception”的行:

Get-Content -Path $file.FullName | Select-String "Exception"

如果您想测试是否有任何行包含“异常”一词,那么就像将上述命令的结果分配给一个变量并测试一个值一样简单!

$results = Get-Content -Path $file.FullName | Select-String "Exception"

if ($results) {
    Write-Output "Exception found"
}
else {
    Write-Output "No exception found"
}

推荐阅读