I have a log file(.log) which is huge. I'm trying to find few keywords which need to be highlighted so that I can skip through other lines in the log faster. But, I don't want to filter only the select-string but highlight select-string. Also, I have no Idea about Powershell, I have the below command so far, from googling.
C:\users\proto> cat txtlog.log select-string "Valid" | write-host -foregroundcolor redWhich doesn't output what I want as it's only returning "valid" lines in red color but not the other lines.
32 Answers
Add Format-Color function from here:
function Format-Color([hashtable] $Colors = @{}, [switch] $SimpleMatch) { $lines = ($input | Out-String) -replace "`r", "" -split "`n" foreach($line in $lines) { $color = '' foreach($pattern in $Colors.Keys){ if(!$SimpleMatch -and $line -match $pattern) { $color = $Colors[$pattern] } elseif ($SimpleMatch -and $line -like $pattern) { $color = $Colors[$pattern] } } if($color) { Write-Host -ForegroundColor $color $line } else { Write-Host $line } }
}Then, pipe your output to Format-Color:
cat txtlog.log | Format-Color @{ 'Valid' = 'Red' }Lines with the word Valid will be displayed in red while the others will be displayed in the default color.
2How about this???
$esc = "$([char]27)"
$FormatWrapRed = "$esc[91m{0}$esc[33m"
txtlog.log | Get-Content | ForEach { If ($_ -match 'Valid') { $FormatWrapRed -f $_ } ELse {$_}
}Or (better IMHO) Add this filter definition to your profile:
Filter Wrap-Red { $esc = "$([char]27)" $WrapFormat = "$esc[91m{0}$esc[33m" If ($_ -match 'Valid') { $WrapFormat -f $_ } ELse {$_}
}Then in any console session, you can use:
txtlog.log | Get-Content | Wrap-RedOr:
gc txtlog.log | Wrap-Red