19

I am a Powershell noob and seem to keep getting caught on little weird behaviors like this. Here is some test code:

 function EchoReturnTest(){
     echo "afdsfadsf"
     return "blah"
 }

 $variable = EchoReturnTest
 echo ("var: " + $variable)

Running this script generates this as output: "var: afdsfadsf blah"

Why does the function not just return the string "blah"?

peterh
  • 11,875
  • 18
  • 85
  • 108
spilliton
  • 3,811
  • 5
  • 35
  • 35
  • 1
    just a guess, but it looks like STDOUT (ie what echo is printing to) and the return value are being dumped into the same stream. You might be able to force them to be separate by telling echo to print to STDERR: echo "afdsfadsf" 1>&2; – mlathe Jan 28 '10 at 23:32

1 Answers1

32

First, PowerShell functions return all uncaptured "output". You can capture output by assigning to a variable and you can ignore output by redirecting to $null e.g.:

$arrayList.Add("hi") > $null

This would normally output something like 0 (the index where "hi" was added) but because we redirected to $null, the output is disregarded.

Second, echo is just an alias for "Write-Output" which writes the corresponding object to the output stream. return "blah" is just a convenience which is equivalent to:

Write-Output "blah"
return

So your function implementation is equivalent to this:

function EchoReturnTest(){  
    Write-Output "afdsfadsf"  
    Write-Output "blah"
    return
}  

If you want to "see" some info on the host console without it being considered part of the "output" of a function then use Write-Host e.g.:

function EchoReturnTest(){  
    Write-Host "afdsfadsf"  
    return "blah"
}

Also, if you have no parameters then you don't need the parens at the end of the function name e.g. function EchoReturnTest { return 'blah' }.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Possible Typo: Isn't echo an alias for "write-output"? – zdan Jan 29 '10 at 00:18
  • 1
    Yep. WriteObject is what you use when writing a cmdlet in C# where I've been spending my time lately. Kind of wish they would have kept the names consistent. :-) – Keith Hill Jan 29 '10 at 00:22
  • 2
    Is there a way to override the behaviour, so the uncaptured values are not returned? E.g. if I want to be specific that whatever happened in the function, only a specific value is returned? – ya23 Dec 03 '13 at 11:55