我已将此功能添加到我的 powershell 配置文件中,因为有一个程序经常弄乱我的 shell 的颜色。
$DefaultForeground = (Get-Host).UI.RawUI.ForegroundColor
$DefaultBackground = (Get-Host).UI.RawUI.BackgroundColor
function SetColors
{
Param
(
[string]$Foreground = "",
[string]$Background = ""
)
$ValidColors = "black","blue","cyan","darkblue" ,"darkcyan","darkgray",
"darkgreen","darkmagenta","darkred","darkyellow","gray","green",
"magenta","red","white","yellow";
$Foreground = $Foreground.ToLower()
$Background = $Background.ToLower()
if ( $Foreground -eq "" )
{
$Foreground = $DefaultForeground
}
if ( $Background -eq "" )
{
$Background = $DefaultBackground
}
if ( $ValidColors -contains $Foreground -and
$ValidColors -contains $Background )
{
$a = (Get-Host).UI.RawUI
$a.ForegroundColor = $Foreground
$a.BackgroundColor = $Background
}
else
{
write-host "Foreground/Background Colors must be one of the following:"
$ValidColors
}
}
set-alias set-colors SetColors
一些注意事项:
"$DefaultCololrs = (Get-Host).UI.RawUI" 创建的指针类型对象多于对象的实际副本。这意味着,如果您稍后设置一个不同的变量等于 "(Get-Host).UI.RawUI",并进行更改,$DefaultColors 也会更改(这就是为什么我确保将它们作为字符串复制到此处)。
我尝试设置其他颜色(使用十六进制代码),但运气不佳,虽然我确实找到了Setting Powershell colors with hex values in profile script(我还没有尝试过,因为我不是特别喜欢在注册表中捣乱,并且默认的颜色列表似乎已经足够了)。
我还找到了这个文档:https://technet.microsoft.com/en-us/library/ff406264.aspx,我可能需要稍后使用它来弄清楚如何修改我的“grep”命令(目前我将它别名为 select-string)