我正在编写一个 PowerShell 脚本msbuild
一堆解决方案。我想计算有多少解决方案构建成功,有多少解决方案失败。我还想查看编译器错误,但仅限于第一个失败的错误(我假设其他错误通常也会出现类似的错误,并且我不想弄乱我的输出)。
我的问题是关于如何运行外部命令(msbuild
在本例中),但有条件地通过管道传输其输出。如果我正在运行它并且还没有遇到任何失败,我不想通过管道传输它的输出;我希望它直接输出到控制台,而不进行重定向,因此它将对其输出进行颜色编码。 (像许多程序一样,如果 msbuild 发现其标准输出被重定向,它会关闭颜色编码。)但是如果我之前遇到过失败,我想通过管道传输到Out-Null
.
显然我可以这样做:
if ($SolutionsWithErrors -eq 0) {
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly
} else {
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly | Out-Null
}
但似乎必须有一种方法可以在不重复的情况下做到这一点。 (好吧,它不一定是重复的——我可以省略/consoleloggerparameters
如果我无论如何都将管道归零——但你明白了。)
可能还有其他方法可以解决这个问题,但今天,我特别想知道:是否有一种方法可以运行命令,但仅在满足特定条件时才通过管道传输其输出(否则不通过管道传输或将其输出重定向到所有,所以它可以做一些奇特的事情,比如颜色编码输出)?
您可以将输出命令定义为变量并使用Out-Default
or 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
UPDATE
上面的代码丢失了 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}
有没有一种方法可以运行命令,但仅在满足特定条件时才通过管道传输其输出(否则根本不通过管道传输或重定向其输出,因此它可以执行诸如颜色编码输出之类的奇特功能)?
更有可能的是,没有内置这样的方法。但它可以用函数来实现,并且函数可以按如下方式重用:
function Invoke-WithOutput($OutputCondition, $Command) {
if ($OutputCondition) { & $Command } else { $null = & $Command }
}
Invoke-WithOutput ($SolutionsWithErrors -eq 0) {
msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)