在PowerShell中保留输出重定向的颜色

4

假设我这样运行msbuild:

function Clean-Sln {
    param($sln)
    MSBuild.exe $sln /target:Clean
}
Clean-Sln c:\temp\SO.sln

在Posh控制台中,输出内容是有颜色的。这非常方便 - 你可以通过观察输出来发现颜色。例如,不重要的消息是灰色的。 问题 我想添加将其重定向到某个地方的能力,就像这样(简化示例):
function Clean-Sln {
    param($sln)
    MSBuild.exe $sln /target:Clean | Redirect-AccordingToRedirectionVariable
}
$global:Redirection = 'Console'
Clean-Sln c:\temp\SO.sln
$global:Redirection = 'TempFile'
Clean-Sln c:\temp\Another.sln
  • 如果我使用“控制台”,则 cmdlet/function Redirect-AccordingToRedirectionVariable 应该以与未传输输出相同的方式输出带有颜色的 msbuild 消息。换句话说,它应该保留输出不变。
  • 如果我使用“TempFile”,Redirect-AccordingToRedirectionVariable 将把输出存储在临时文件中。

这是否可能?我猜不是 :| 或者您有什么建议可以实现目标吗?

可能的解决方案:

if ($Redirection -eq 'Console) {
  MSBuild.exe $sln /target:Clean | Redirect-AccordingToRedirectionVariable
} else {
  MSBuild.exe $sln /target:Clean | Out-File c:\temp.txt  
}

但是,如果你想象可以有很多很多的msbuild调用,这并不理想。

不要害羞,告诉我如何应对它的任何新建议;)


关于重定向/着色/输出的任何背景信息也是受欢迎的。
(问题不是特定于msbuild,问题涉及任何编写彩色输出的应用程序)

1个回答

3

我建议避免使用带有颜色的输出。在那种情况下,据我所知,所有的颜色信息都会丢失。 我建议在MSBuild中使用/filelogger和/noconsolelogger参数,例如:

function Invoke-MSBuild($project, [string[]]$targets, [switch]$logToFile) {
    $OFS = ';'
    $targetArg = if ($targets) {"/t:$targets"} else {''}
    if ($logToFile) {
        msbuild.exe $project $targetArg  /filelogger /noconsolelogger
    }
    else {
        msbuild.exe $project $targetArg 
    }
}

或者你可以像这样做得更简单一些:
function Invoke-MSBuild($project, [string[]]$targets, $logFile) {
    $OFS = ';'
    $targetArg = if ($targets) {"/t:$targets"} else {''}
    if ($logFile) {
        msbuild.exe $project $targetArg > $logFile
    }
    else {
        msbuild.exe $project $targetArg 
    }
}

@Keith,谢谢你的回答。我一定会使用msbuild日志记录器。然而,通常任何应用程序都可以输出带颜色的消息,msbuild只是其中之一。 - stej
是的,我不知道有什么方法可以将带颜色的exe输出或write-host -foregroundcolor输出进行管道传输而不丢失颜色信息。 - Keith Hill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接