powershell では以前に書いた Write-Host とループによる方法 のほかにエスケープシークエンスでも標準出力の色を変更できるようです。
環境
Name Value
---- -----
PSVersion 5.1.18362.752
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18362.752
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
コード
Microsoft.PowerShell_profile.ps1
function New-AnsiColorObject {
$decimalColor = @{
Black = "0"
Red = "1"
Green = "2"
Yellow = "11"
Blue = "4"
Magenta = "5"
Cyan = "6"
White = "15"
Gray = "7"
DarkRed = "124"
DarkGreen = "22"
DarkYellow = "100"
DarkBlue = "17"
DarkMagenta = "124"
DarkCyan = "31"
DarkGray = "8"
}
$fgTable = @{}
$bgTable = @{}
$decimalColor.GetEnumerator() | ForEach-Object {
$fgTable[$_.Name] = "$([char]27)[38;5;{0}m" -f $_.Value
$bgTable[$_.Name] = "$([char]27)[48;5;{0}m" -f $_.Value
}
return [PSCustomObject]@{
FG = $fgTable
BG = $bgTable
RESET = "$([char]27)[0m"
}
}
$Global:ANSI_ESC_SEQ = New-AnsiColorObject
function Write-StringHighLight {
param (
[string]$pattern = ".",
[switch]$case,
[ValidateSet("White", "Black", "Blue", "DarkBlue", "Green", "DarkGreen", "Cyan", "DarkCyan", "Red", "DarkRed", "Magenta", "DarkMagenta", "Yellow", "DarkYellow", "Gray", "DarkGray")][string]$color = "Yellow",
[switch]$continuous
)
$option = ($case)? "None" : "IgnoreCase"
foreach ($line in $input) {
[regex]::Replace(
$line,
"($pattern)",
($Global:ANSI_ESC_SEQ.BG[$color] + $Global:ANSI_ESC_SEQ.FG.Black + '$1' + $Global:ANSI_ESC_SEQ.RESET),
$option) | Write-Host -NoNewline:$continuous
}
}
Set-Alias hilight Write-StringHighLight
かなりスッキリ書き直せました。powershell 7 以降であれば [char]27
の代わりに `e
が使えるようです(公式ドキュメント)。