Powershell script to find strings and highlight them in the output

After reading about Brad's find script I starting thinking about how cool it would be if I could highlight the search pattern in the output. So I wrote my own custom Find-String script to highlight the results.

Find-String.ps1

# Find-String.ps1
#  Wrapper around dir | select-string which will highlight the pattern in the results
param	( [string] $pattern = ""
	, [string] $filter = "*.*"
	, [switch] $recurse = $false
	, [switch] $caseSensitive = $false)

if ($pattern -eq $null -or $pattern -eq "") { Write-Error "Please provide a search pattern!" ; return }

$regexPattern = $pattern
if($caseSensitive -eq $false) { $regexPattern = "(?i)$regexPattern" }
$regex = New-Object System.Text.RegularExpressions.Regex $regexPattern

# Write the line with the pattern highlighted in red
function Write-HostAndHighlightPattern([string]$inputText)
{
	$index = 0
	while($index -lt $inputText.Length)
	{
		$match = $regex.Match($inputText, $index)
		if($match.Success -and $match.Length -gt 0)
		{
			Write-Host $inputText.SubString($index, $match.Index - $index) -nonewline
			Write-Host $match.Value.ToString() -ForegroundColor Red -nonewline
			$index = $match.Index + $match.Length
		}
		else
		{
			Write-Host $inputText.SubString($index) -nonewline
			$index = $inputText.Length
		}
	}
}

# Do the actual find in the files
Get-ChildItem -recurse:$recurse -filter:$filter | 
	Select-String -caseSensitive:$caseSensitive -pattern:$pattern |	
	foreach {
		Write-Host "$($_.FileName)($($_.LineNumber)): " -nonewline
		Write-HostAndHighlightPattern $_.Line
		Write-Host
	}

Sample Output

PS> ./Find-String new-object
Find-String.ps1(13): $regex = New-Object System.Text.RegularExpressions.Regex $regexPattern
Get-ApptsUsingEWS.ps1(55): $responseXml = [xml](new-object System.IO.StreamReader $responseStream).ReadToEnd()
Get-ApptsUsingOOM.ps1(6): $outlook = New-Object -ComObject Outlook.Application
getappts.ps1(51): $responseXml = [xml](new-object System.IO.StreamReader $responseStream).ReadToEnd()
printAppts.ps1(6): $outlook = New-Object -ComObject Outlook.Application

 

For reference here are some other find scripts around the blogsphere: Brad Wilson, Ian Griffith and Keith Hill.

1 Comment

  • Hey

    This is going to useful to me. 'Borrowing' it if you donot mind....

    sureshparmar2000@hotmail.com

    Oh, btw, I am looking to get the status of a scheduled job using 'get-wmiobject -class win32_scheduledjob', but it does not return anything.

    Any help would be really appriciated.

    Thanks.

Comments have been disabled for this content.