Arbelac
Arbelac

Reputation: 1904

Find pattern with Powershell

I have a log file with multiple lines of text from multiple log files. I am attempting to send the log files contents in the body of an email using Send-MailMessage.

My question is : I am trying to extract lines a string of text Exception from multiple log files. I want to match this within if statement. I have tried script like below but no luck. Any insight would be greatly appreciated.

Log file content :

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)

After extract desired output:

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

Here is a snippet of the script for reference.

$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'.."
}


}

Thanks in advance,

Upvotes: 0

Views: 127

Answers (1)

gvee
gvee

Reputation: 17161

Find all lines that contain the word "Exception":

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

If you want to test to see if there are any lines containing the word "Exception" then it's as easy as assigning the results of the above command to a variable and testing for a value!

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

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

Upvotes: 1

Related Questions