我有一个powershell脚本,通过写输出提供一些状态输出.我故意不使用write-host,因为输出可能被捕获并写入日志文件,如下所示:
./myscript.ps1 | out-file log.txt
Run Code Online (Sandbox Code Playgroud)
但是如果输出没有被重定向,那么在控制台上输出彩色输出会很好,因为脚本会产生许多不同的状态消息.我知道使用write-host可以实现彩色输出,但状态消息应该是可管理的.
任何想法如何解决这个问题?
Rom*_*min 11
我试过这个额外的功能,它基本上工作正常:
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
Run Code Online (Sandbox Code Playgroud)
这个特殊测试的结果虽然有点滑稽:我们确实得到了红色,绿色和黄色的线条,但是表格标题是红色的,即函数第一次调用的颜色.
这边走:
function Green
{
process { Write-Host $_ -ForegroundColor Green }
}
function Red
{
process { Write-Host $_ -ForegroundColor Red }
}
Write-Output "this is a test" | Green
Write-Output "this is a test" | Red
Run Code Online (Sandbox Code Playgroud)
将管道上的结果与控制台中的状态消息分开.
例如,在脚本中使用这样的函数:
function write-status( $status ){
$status | write-host -fore green -back red; #send a status msg to the console
$status | write-output; #send a status object down the pipe
}
Run Code Online (Sandbox Code Playgroud)
我还建议您使用以下cmdlet之一而不是write-host来从脚本输出状态消息:
这些状态消息的外观将根据使用的cmdlet而有所不同.此外,用户可以使用$(warning | error | verbose | debug)首选项变量禁用特定级别的状态,或使用 - (warning | error | verbose | debug)变量常用cmdlet参数捕获特定状态消息.
我遇到了同样的问题,所以我分享我的解决方案,我认为效果很好:
Write-ColorOutput "Hello" Green Black -NoNewLine
Write-ColorOutput " World" Red
Run Code Online (Sandbox Code Playgroud)
这是使用它的 Cmdlet
function Write-ColorOutput
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False,Position=1,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][Object] $Object,
[Parameter(Mandatory=$False,Position=2,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][ConsoleColor] $ForegroundColor,
[Parameter(Mandatory=$False,Position=3,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][ConsoleColor] $BackgroundColor,
[Switch]$NoNewline
)
# Save previous colors
$previousForegroundColor = $host.UI.RawUI.ForegroundColor
$previousBackgroundColor = $host.UI.RawUI.BackgroundColor
# Set BackgroundColor if available
if($BackgroundColor -ne $null)
{
$host.UI.RawUI.BackgroundColor = $BackgroundColor
}
# Set $ForegroundColor if available
if($ForegroundColor -ne $null)
{
$host.UI.RawUI.ForegroundColor = $ForegroundColor
}
# Always write (if we want just a NewLine)
if($Object -eq $null)
{
$Object = ""
}
if($NoNewline)
{
[Console]::Write($Object)
}
else
{
Write-Output $Object
}
# Restore previous colors
$host.UI.RawUI.ForegroundColor = $previousForegroundColor
$host.UI.RawUI.BackgroundColor = $previousBackgroundColor
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37050 次 |
| 最近记录: |