嗯,我以前从未使用过它,所以我想我会尝试一下。基本上,您只需按字面意思放置一个转义字符(ASCII 27),后跟一个左括号[
然后是代码,如本页所述 http://bluesock.org/~willg/dev/ansi.html,直接进入字符串。
为了使这更容易,我编写了一个格式化字符串的函数:
function Format-AnsiColor {
[CmdletBinding()]
[OutputType([String])]
param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true
)]
[AllowEmptyString()]
[String]
$Message ,
[Parameter()]
[ValidateSet(
'normal display'
,'bold'
,'underline (mono only)'
,'blink on'
,'reverse video on'
,'nondisplayed (invisible)'
)]
[Alias('attribute')]
[String]
$Style ,
[Parameter()]
[ValidateSet(
'black'
,'red'
,'green'
,'yellow'
,'blue'
,'magenta'
,'cyan'
,'white'
)]
[Alias('fg')]
[String]
$ForegroundColor ,
[Parameter()]
[ValidateSet(
'black'
,'red'
,'green'
,'yellow'
,'blue'
,'magenta'
,'cyan'
,'white'
)]
[Alias('bg')]
[String]
$BackgroundColor
)
Begin {
$e = [char]27
$attrib = @{
'normal display' = 0
'bold' = 1
'underline (mono only)' = 4
'blink on' = 5
'reverse video on' = 7
'nondisplayed (invisible)' = 8
}
$fore = @{
black = 30
red = 31
green = 32
yellow = 33
blue = 34
magenta = 35
cyan = 36
white = 37
}
$back = @{
black = 40
red = 41
green = 42
yellow = 43
blue = 44
magenta = 45
cyan = 46
white = 47
}
}
Process {
$formats = @()
if ($Style) {
$formats += $attrib[$Style]
}
if ($ForegroundColor) {
$formats += $fore[$ForegroundColor]
}
if ($BackgroundColor) {
$formats += $back[$BackgroundColor]
}
if ($formats) {
$formatter = "$e[$($formats -join ';')m"
}
"$formatter$_"
}
}
Usage:
Format-AnsiColor -Message 'Hey there' -Style Bold -ForegroundColor Red
'Hello' | Format-AnsiColor -BackgroundColor Green
'One','Two','Three' | Format-AnsiColor -Style 'normal display' -ForegroundColor White -BackgroundColor Black
请记住,如果您不再需要它,则必须关闭该序列(我的意思是将样式和颜色设置回之前的值)。