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 and then output the result with format-table.
dir -r -i *.* | Select-String $args[0] |
format-table -Property @{label="Line #"; Expression={$_.LineNumber}; width=6},
Path, Line -wrap
It would be nice to be able to format the word we are searching for with a specific color, so that you can see exactly where it was found on the line.
You could pipe the table into Out-String
, then write the string in parts using Write-Host
with the -NoNewLine
switch.
Something like this:
filter ColorWord {
param(
[string] $word,
[string] $color
)
$line = $_
$index = $line.IndexOf($word, [System.StringComparison]::InvariantCultureIgnoreCase)
while($index -ge 0){
Write-Host $line.Substring(0,$index) -NoNewline
Write-Host $line.Substring($index, $word.Length) -NoNewline -ForegroundColor $color
$used = $word.Length + $index
$remain = $line.Length - $used
$line = $line.Substring($used, $remain)
$index = $line.IndexOf($word, [System.StringComparison]::InvariantCultureIgnoreCase)
}
Write-Host $line
}
Get-Process| Format-Table| Out-String| ColorWord -word 1 -color magenta
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With