1

I have a function, and within that function, I am calling a git function:

function Confirm-GitStatus
{
    # a bunch of stuff
    & git --git-dir $gitDir --work-tree $basePath  checkout $targetBranch 2>&1
    # more stuff
    return $true
}

The result of this is actually an array containing the result of the the git call and $true. In order to get the result I wanted, I had to do this:

$disposableMessage = & git --git-dir $gitDir --work-tree $basePath  checkout $targetBranch 2>&1

This feels gross. What is the best practice for making calls and tossing the result?

2 Answers2

1

Since you're using a stream redirection anyway - 2>&1 to merge the PowerShell error stream (from git's stderr) to the success stream (from stdout)) - the simplest solution is to redirect all streams (*) to $null with *> $null; a simplified example:

# Note: This command produces both stdout and stderr output.
cmd /c "echo hi & dir \nosuch" *> $null

# PowerShell Core example with Bash:
bash -c 'echo hi; ls \nosuch'  *> $null

However, in general consider $null = ... for discarding a command's (success) output, because it:

  • conveys the intent up front

  • is faster than both > $null and especially ... | Out-Null in most cases.[1]

Applied to the examples above:

$null = cmd /c "echo hi & dir \nosuch" 2>&1

$null = bash -c 'echo hi; ls \nosuch'  2>&1

[1] In PowerShell (Core) 6+, Out-Null has an optimization if the only preceding pipeline segment is a side effect-free expression rather than a method or command call; e.g., 1..1e6 | Out-Null executes in almost no time, because the expression is seemingly not even executed. However, such a scenario is atypical, and the functionally equivalent Write-Output (1..1e6) | Out-Null takes a long time to run, much longer than $null = Write-Output (1..1e6).

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

You can pipe your command to Out-Null.

AdminOfThings
  • 23,946
  • 4
  • 17
  • 27