Calling Echo inside a function pre-pends echo stri

2019-02-16 09:36发布

问题:

Hey guys, I'm 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"?

回答1:

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' }.