我正在msbuild为一系列解决方案编写PowerShell脚本。我想计算成功构建了多少解决方案,失败构建了多少。我还希望看到编译器错误,但仅从第一个失败的错误开始(我假设其他错误通常也有类似的错误,并且我不想使我的输出混乱)。
我的问题是关于如何运行外部命令(msbuild在这种情况下),但有条件地通过管道传递其输出。如果我正在运行它并且还没有出现任何故障,那么我就不希望通过管道传递其输出。我希望它直接输出到控制台,而无需重定向,因此它将对输出进行颜色编码。(就像许多程序一样,如果msbuild看到其stdout被重定向了,则会关闭颜色编码。)但是,如果我之前遇到过故障,我想传递给Out-Null。
显然我可以这样做:
if ($SolutionsWithErrors -eq 0) {
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly
} else {
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly | Out-Null
}
Run Code Online (Sandbox Code Playgroud)
但是似乎必须要有一种方法来避免重复。(好吧,这不一定是重复的- /consoleloggerparameters如果我无论如何都将管道设为null,我可能会放弃-但您明白了。)
可能还有其他方法可以解决此问题,但对于今天,我特别想知道:有没有一种方法可以运行命令,但是只有在满足特定条件的情况下才通过管道传输它的输出(否则,不通过管道将其输出或重定向到所有,所以它可以做一些花哨的东西,例如颜色编码的输出)?
您可以将输出命令定义为变量,并使用Out-Default或Out-Null:
# set the output command depending on the condition
$output = if ($SolutionsWithErrors -eq 0) {'Out-Default'} else {'Out-Null'}
# invoke the command with the variable output
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly | & $output
Run Code Online (Sandbox Code Playgroud)
更新
上面的代码丢失了MSBuild颜色。为了保留颜色并且避免重复代码,可以使用以下方法:
# define the command once as a script block
$command = {msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly}
# invoke the command with output depending on the condition
if ($SolutionsWithErrors -eq 0) {& $command} else {& $command | Out-Null}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以运行命令,但是只有在满足特定条件的情况下才通过管道传输它的输出(否则根本不通过管道传输或完全重定向其输出,因此它可以执行类似颜色编码的输出的操作)?
没有内置的这种方法,更有可能。但是它可以用一个函数来实现,并且该函数可以这样重复使用:
function Invoke-WithOutput($OutputCondition, $Command) {
if ($OutputCondition) { & $Command } else { $null = & $Command }
}
Invoke-WithOutput ($SolutionsWithErrors -eq 0) {
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
554 次 |
| 最近记录: |