powershell 脚本格式表输出中的颜色词 [英] Color words in powershell script format-table output
问题描述
是否可以使用格式表为 powershell 输出仅着色某些单词(而不是完整的行).例如,此脚本递归扫描文件夹中的字符串,然后使用 format-table 输出结果.
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.
推荐答案
您可以将表通过管道传输到 Out-String
,然后使用 Write-Host
将字符串分成几部分> 使用 -NoNewLine
开关.
You could pipe the table into Out-String
, then write the string in parts using Write-Host
with the -NoNewLine
switch.
像这样:
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
这篇关于powershell 脚本格式表输出中的颜色词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!