有没有办法在使用写输出时指定字体颜色 [英] Is there a way to specify a font color when using write-output

查看:37
本文介绍了有没有办法在使用写输出时指定字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 powershell 脚本,它通过 write-output 提供一些状态输出.我故意不使用 write-host 因为输出可能会被捕获并写入这样的日志文件:

I have a powershell script that gives some status output via write-output. I am intentionally not using write-host because the output may be captured and written to a logfile like this:

./myscript.ps1 | out-file log.txt

但是如果输出没有被重定向,那么在控制台上有彩色输出会很好,因为脚本会产生很多不同的状态消息.我知道使用 write-host 可以实现彩色输出,但状态消息应该可以通过管道传输.

But if the output is not redirected it would be nice to have colored output on the console, because the script is producing a lot of different status messages. I know that colored output is possible with write-host but the status messages should be pipeable.

任何想法如何解决这个问题?

Any ideas how to solve this?

推荐答案

我已经尝试过这个额外的功能,它基本上可以正常工作:

I have tried this extra function and it basically works fine:

function Write-ColorOutput($ForegroundColor)
{
    # save the current color
    $fc = $host.UI.RawUI.ForegroundColor

    # set the new color
    $host.UI.RawUI.ForegroundColor = $ForegroundColor

    # output
    if ($args) {
        Write-Output $args
    }
    else {
        $input | Write-Output
    }

    # restore the original color
    $host.UI.RawUI.ForegroundColor = $fc
}

# test
Write-ColorOutput red (ls)
Write-ColorOutput green (ls)
ls | Write-ColorOutput yellow

这个特定测试的结果有点有趣:我们确实得到了红色、绿色和黄色的线条,但表头是红色的,即函数第一次调用的颜色.

The result of this particular test is a little bit funny though: we really get lines in red, green and yellow but the table header is in red, i.e. the color of the the first call of the function.

这篇关于有没有办法在使用写输出时指定字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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