Calling Echo inside a function pre-pends echo string to return value in Powershell

前端 未结 1 1432
天命终不由人
天命终不由人 2021-01-08 00:10

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 \"         


        
相关标签:
1条回答
  • 2021-01-08 00:55

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

    0 讨论(0)
提交回复
热议问题