有条不紊地走向Out-Null

时间:2015-06-07 13:20:06

标签: powershell

我正在为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
}

但似乎必须有一种方法可以在没有重复的情况下完成它。 (好吧,它不一定要重复 - 如果我无论如何都要归零,我可以不用/consoleloggerparameters - 但你明白了。)

可能有其他方法可以解决这个问题,但是对于今天,我特别想知道:有没有办法运行命令,但只有在满足某个条件时才管道输出(否则不管道它或重定向它的输出,所以它可以做彩色编码输出等奇特的东西?

1 个答案:

答案 0 :(得分:5)

您可以将输出命令定义为变量,并使用Out-DefaultOut-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

更新

上面的代码丢失了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}
  

有没有办法运行一个命令,但是如果满足某个条件,只管道它的输出(否则不管道它或重定向它的输出,所以它可以做彩色编码输出等奇特的东西)? / p>

没有这种方式内置,更有可能。但它可以通过函数实现,并且函数可以重复使用:

function Invoke-WithOutput($OutputCondition, $Command) {
    if ($OutputCondition) { & $Command } else { $null = & $Command }
}

Invoke-WithOutput ($SolutionsWithErrors -eq 0) {
    msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly
}