我可以在 Powershell 中转义颜色代码,以便不需要使用 -ForeGroundColor 吗? [英] Can I escape a color code in Powershell so I do not need to use -ForeGroundColor?

查看:49
本文介绍了我可以在 Powershell 中转义颜色代码,以便不需要使用 -ForeGroundColor 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用一些颜色代码转义字符,这样我就不需要提及 -ForeGroundColor 参数?

Is it possible to use some color-code escape character so that I do not need to mention -ForeGroundColor parameter?

所以而不是:

write-Host "Hello World!" -ForegroundColor:Blue

我可以这样做吗:

write-Host "Hello \{somethinghere to denote from this point it will be in BLUE color} World!" 

推荐答案

这是一个解决不支持 ANSI 转义码的 powershell 的解决方案.

Here's a solution that gets around powershell not supporting ANSI escape codes.

这应该允许您指定用作分隔符的字符

This should allow you to specify what character you use as a delimiter

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 }
        }
    }
}

在开关块中,添加任何您想要对应于某种颜色的速记代码.我选择了单个字符,因为它更容易验证,结果如下:

in the switch block, add whatever shorthand codes you want to correspond to a certain color. I picked single characters since its easier to validate against, and the results are as follows:

$text = "#rmy #gname #yis #bchris"

输出类似

请记住,在使用此辅助函数时,您需要使用

just keep in mind, while using this helper function, you will need to use

`n

用于在文本中添加换行符,或者根据需要在函数底部添加 write-host "".

for adding newlines to your text, or add a write-host "" to the bottom of your function if desired.

修改后的代码更可靠

这篇关于我可以在 Powershell 中转义颜色代码,以便不需要使用 -ForeGroundColor 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆