Jam*_*979 8 terminal powershell colors
如何在 powershell 终端中对标准输出stdout和标准错误stderr进行着色?
也就是说,在典型的 powershell 终端中运行任何命令行程序。该程序写入stdout和stderr。程序不应被修改或了解颜色设置。
我希望stdout为白色,stderr为红色。
You can take advantage of the fact that the standard output gets normally streamed in most common cases, and also that redirection does not forget the initial handle. Therefore, a sample solution is to
In my tests this works quite well:
function Color {
param (
[Parameter(Mandatory)]
[scriptblock]$Command,
[System.ConsoleColor]$OutColor = [System.ConsoleColor]::White,
[System.ConsoleColor]$ErrColor = [System.ConsoleColor]::Red,
[System.ConsoleColor]$WrnColor = [System.ConsoleColor]::Yellow,
[System.ConsoleColor]$VrbColor = [System.ConsoleColor]::Magenta,
[System.ConsoleColor]$InfColor = [System.ConsoleColor]::Blue
)
& $command *>&1 | ForEach-Object {
$PrintColor =
if ($_ -is [System.Management.Automation.ErrorRecord]) { $ErrColor }
elseif ($_ -is [System.Management.Automation.WarningRecord]) { $WrnColor }
elseif ($_ -is [System.Management.Automation.VerboseRecord]) { $VrbColor }
elseif ($_ -is [System.Management.Automation.InformationRecord]) { $InfColor }
else {$OutColor}
Write-Host -ForegroundColor $PrintColor $_
}
}
Run Code Online (Sandbox Code Playgroud)
Test:
Color {
Write-Output OUT;
Write-Error ERR;
Write-Warning WRN;
Write-Verbose VRB;
Write-Information INF;
Write-Host -ForegroundColor Black HOST;
1234
}
Run Code Online (Sandbox Code Playgroud)
输出看起来像(色盲友好编辑):
OUT // white
ERR // red
WRN // yellow
INF // blue
HOST // blue
1234 // white
Run Code Online (Sandbox Code Playgroud)
旁注:Write-Host在这里被强制处理Information,因此该脚本会覆盖所有着色。