是否可以使用一些颜色代码转义字符,以便我不需要提及 -ForeGroundColor 参数?
所以而不是:
write-Host "Hello World!" -ForegroundColor:Blue
我可以做类似的事情吗:
write-Host "Hello \{somethinghere to denote from this point it will be in BLUE color} World!"
这是一个解决 powershell 不支持 ANSI 转义码的解决方案。
这应该允许您指定用作分隔符的字符
function Write-Colored {
param(
[Parameter(Mandatory=$True, Position=1)]
[string]$text,
[Parameter(Mandatory=$True, Position=2)]
[string]$delimiter
)
$i = $text.Split($delimiter)
function pr ([string]$item, [System.ConsoleColor]$color){
Write-Host $item.Substring(1) -fore $color -NoNewline
}
foreach ($item in $i){
$colorcode = $item.ToCharArray()[0]
switch($colorcode){
"b" { pr $item Blue }
"r" { pr $item Red }
"g" { pr $item Green }
"y" { pr $item Yellow }
default { Write-Host $item -NoNewline }
}
}
}
在开关块中,添加您想要对应于某种颜色的任何速记代码。我选择了单个字符,因为它更容易验证,结果如下:
input:
$text = "#rmy #gname #yis #bchris"
输出类似的东西
请记住,在使用此辅助函数时,您将需要使用
`n
用于向文本添加换行符,或添加write-host ""
如果需要的话,到你的函数的底部。
编辑:修改后的代码更加可靠
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)