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?
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.