Is it possible to color only certain words (not complete lines) for a powershell output using format-table. For example, this script scans a folder recursively for a string
I love answer @Ryant gave. I have a modified version here that can be used for colouring multiple words in an output by passing in arrays or words and colours. The trick is that you have to split the input text into lines based on the newline separator.
filter ColorWord2 {
param(
[string[]] $word,
[string[]] $color
)
$all = $_
$lines = ($_ -split '\r\n')
$lines | % {
$line = $_
$x = -1
$word | % {
$x++
$item = $_
$index = $line.IndexOf($item, [System.StringComparison]::InvariantCultureIgnoreCase)
while($index -ge 0){
Write-Host $line.Substring(0,$index) -NoNewline
Write-Host $line.Substring($index, $item.Length) -NoNewline -ForegroundColor $color[$x]
$used =$item.Length + $index
$remain = $line.Length - $used
$line =$line.Substring($used, $remain)
$index = $line.IndexOf($item, [System.StringComparison]::InvariantCultureIgnoreCase)
}
}
Write-Host $line
} }
and would be executed as follows
Get-Service | Format-Table| Out-String| ColorWord2 -word 'Running','Stopped' -color 'Green','Red'