I saw a question on how to highlight certain lines of text when viewing logfiles in PowerShell console. It took me a few minutes to produce a function that does the job:
Function Find-String {
<#
.SYNOPSIS
Finds given pattern and highlights each line that it contains.
.DESCRIPTION
Finds given pattern and highlights each line that it contains.
By default the lines are highlighted in green.
Accepts any input as it converts objects to strings on the fly.
This functuion should rather be used as a last step for text file ad-hoc investigation.
You cannot effectively pipe the output any further.
.EXAMPLE
This example shows coloured process list:
get-process | Find-String -Pattern svchost -Colour magenta
.EXAMPLE
This example shows coloured process list:
Get-Content application1.log | Find-String -Pattern error,warning -Colour red
.PARAMETER Pattern
Specify a pattern to highlight.
.PARAMETER Colour
Specify a highlight colour.
#>
[CmdletBinding()]
Param(
[Parameter( Mandatory=$True, ValueFromPipeline=$true) ]
[object[]]$Stream,
[Parameter( Mandatory=$True) ]
[string[]]$Pattern,
[Parameter( Mandatory=$False) ]
$Colour = "Green"
)
BEGIN{
$out = @()
$pat = $pattern -join ("|")
write-verbose "Pattern applied: $pat"
}
PROCESS{
$out += $stream
}
END{
($out | out-string) -split "\n" | ForEach-Object{ IF($_ -match "$Pat"){Write-Host -ForegroundColor $colour $_}ELSE{Write-Host -ForegroundColor "white" $_}}
}
}