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”?
First, PowerShell functions return all uncaptured “output”. You can capture output by assigning to a variable and you can ignore output by redirecting to
$nulle.g.:This would normally output something like 0 (the index where “hi” was added) but because we redirected to $null, the output is disregarded.
Second,
echois 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:So your function implementation is equivalent to this:
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.:
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' }.