2

I have a piece of script with the following line:

myBinary.exe --param1 a -param2 b | Tee-Object -Variable "myVar"

It used to stream the output just fine. Now that I moved this line into a function, it no longer streams to standard out and only populate the variable myVar.

Any idea how to get around this issue?

0

1 Answer 1

2

We don't have enough information to diagnose your problem, but there's a Tee-Object pitfall that may explain your symptoms:

As of Windows PowerShell v5.1 / PowerShell Core v6.0.0-rc:

If Tee-Object doesn't receive any success output via the pipeline, it leaves the target variable's previous value untouched or, if there's no preexisting variable by that name, does not create it.

# Run command that produces stdout and therefore PS success-stream output.
cmd /c 'echo hi' | Tee-Object -Variable myVar

# Stdout -> success output was correctly captured in $myVar.
$myVar  # -> 'hi'

# Run another command that *doesn't* produce any stdout output
# (only stderr output).
cmd /c 'echo NO >&2' | Tee-Object -Variable myVar

# !! Perhaps unexpectedly, the previous value of $myVar was NOT cleared.
$myVar # -> !! STILL 'hi'

This unintuitive behavior has been reported on GitHub.

The - cumbersome - workaround is to explicitly set the target variable to $null first:
$myVar = $null


Thus, perhaps what you're seeing in $myVar is a preexisting value that the - now seemingly non-stdout-output-producing - myBinary.exe ... | Tee-Object ... call didn't clear.

4
  • Thank you for your quick response. I have isolated the issue and it seems like the problem only occurs if the Tee-Object is in a function Nov 28, 2017 at 3:47
  • @user1763590: The issue may still be the same; note that a function sees variables defined in ancestral scopes, so if there's a $myVar in the global scope, for instance, the function would see it too, and with a command that doesn't produce stdout / success output, the Tee-Object call will not create a local copy that shadows the ancestral one.
    – mklement0
    Nov 28, 2017 at 4:04
  • I know this is old but the issue is still present; is there a workaround? Redirect stderr to stdout? In my case I'm invoking a git push command which I think is only resulting in stderr output (not intuitive at all) so I'm seeing this same issue.
    – kamranicus
    Mar 5, 2020 at 3:30
  • @kamranicus, the - cumbersome - workaround is to explicitly set the target variable to $null first.
    – mklement0
    Mar 5, 2020 at 4:10

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.