Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 207

Powershell function returns stdout? (Old title: Powershell append to array of arrays appends stdout?)

$
0
0

I've learnt from this thread how to append to an array of arrays. However, I've observed the weirdest behaviour ever. It seems to append stdout too! Suppose I want to append to an array of arrays, but I want to echo debug messages in the loop. Consider the following function.

function WTF {  $Result = @()  $A = 1,2  $B = 11,22  $A,$B | % {    Write-Output "Appending..."    $Result += , $_  }  return $Result}

Now if you do $Thing = WTF, you might think you get a $Thing that is an array of two arrays: $(1,2) and $(11,22). But that's not the case. If you type $Thing in the terminal, you actually get:

Appending...Appending...121122

That is, $Thing[0] is the string "Appending...", $Thing[1] is the string "Appending...", $Thing[2] is the array @(1,2), and $Thing[3] is the array @(11,22). Nevermind that they seem to be in a weird order, which is a whole other can of worms I don't want to get into, but why does the echoed string "Appending..." get appended to the result??? This is so extremely weird. How do I stop it from doing that?

EDIT

Oh wait, upon further experimenting, the following simpler function might be more revealing:

function WTF {  $Result = @()  1,2 | % {    Write-Output "LOL"  }  return $Result

Now if you do $Thing = WTF, then $Thing becomes an array of length 2, containing the string "LOL" twice. Clearly there is something fundamental about Powershell loops and or Write-Output that I'm not understanding.

ANOTHER EDIT!!!

In fact, the following even simpler function does the same thing:

function WTF {  1,2 | % {    Write-Output "LOL"  }}

Maybe I just shouldn't be using Write-Output, but should use Write-Information or Write-Debug instead.


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>