【发布时间】:2017-01-30 14:20:26
【问题描述】:
我正在使用 Powershell 为此处字符串中的特定单词着色。除了包含返回/换行符的单词外,它正在工作。如果没有这些字符,如何计算单词的长度?
以下是我正在使用的函数和测试数据。我希望第二行的“is”也被着色,但我相信 Return/Newline 会导致长度不匹配的问题。
感谢您提供的任何和所有帮助!谢谢! -JFV
Function ColorSpecificWordsOutput {
param(
[Parameter(Mandatory=$true, Position=0)]
[string]$InputText,
[Parameter(Mandatory=$true, Position=1)]
$KeyColor
)
$keys = $keycolor.keys -join "|"
#Split on spaces, pipe to foreach-object
$InputText.Split(" ") | ForEach-Object {
#If word matches one of the $keys
If ($_ -imatch $keys) {
#Retrieve word as string from $keys
[string]$m = $matches.Values[0].trim()
#If length of word equals the $keys word
If($_.Length -eq $m.Length) {
#Write out the word with the mapped forground color without a new line
Write-Host "$_ " -ForegroundColor $keyColor.item($m) -NoNewline
}
#Otherwise, just write the word without color
Else { Write-Host "$_ " -NoNewline }
}
#Otherwise, just write the word without color
else {
Write-Host "$_ " -NoNewline
}
}
}
$w = @"
This color is Yellow: test
Is it correct ?
"@
$find = @{
is = "Cyan"
test = "Yellow"
correct = "Green"
}
ColorSpecificWordsOutput -InputText $w -KeyColor $find
【问题讨论】:
标签: string powershell newline powershell-5.0