Conditional connection to Out-Null

I am writing a PowerShell script to msbuild

a solution set. I want to calculate how many solutions are successfully built and how many errors. I also want to see compiler errors, but only with the first one that fails (I guess others will tend to have similar errors, and I don't want to clutter my output).

My question is how to run an external command ( msbuild

in this case) but conditionally output its output. If I run it and haven't got any crashes yet, I don't want to display its output; I want it to output directly to the console without redirection, so it will color code its output. (As with many programs, msbuild disables color coding if it sees its stdout being redirected.) But if I've had bad luck before, I want to connect to Out-Null

.

Obviously, I could do this:

if ($SolutionsWithErrors -eq 0) {
    msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly
} else {
    msbuild $Path /nologo /v:q /consoleloggerparameters:ErrorsOnly | Out-Null
}

      

But it looks like there is a way to do it without duplication. (Okay, this shouldn't be duplication - I could leave /consoleloggerparameters

if I drop the null value anyway, but you get the idea.)

There may be other ways to solve this problem, but as of today I specifically want to know: is there a way to run a command, but only output its output if a certain condition is met (and would otherwise not redirect it or redirect its output at all, so can he do fancy things like color code)?

+3


source to share


1 answer


You can define the output command as a variable and use either 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

The above code loses MSBuild colors. To preserve colors and avoid code duplication, this approach can be used:



# 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}

      


is there a way to run a command, but only process its output if a certain condition is met (and otherwise not pass it, or redirect its output at all, so that it can do fancy things like color code)?

There is no such way built in, more likely. But it can be implemented with a function, and the function is reused like this:

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

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

      

+4


source







All Articles