How to return one and only one value from a PowerShell function?

前端 未结 10 847
暖寄归人
暖寄归人 2020-12-24 01:17

I\'ve learned from this Stack Overflow question, that PowerShell return semantics are different, let\'s say, from C#\'s return semantics. Quote from the aforementioned quest

10条回答
  •  一生所求
    2020-12-24 01:54

    Don't use echo to write information, use Write-Host, Write-Verbose or Write-Debug depending on the message.

    Echo is an alias for Write-Output which will send it as an Object through the pipeline. Write-Host/Verbose/Debug however is only console-messages.

    PS P:\> alias echo
    
    CommandType Name                 ModuleName
    ----------- ----                 ----------
    Alias       echo -> Write-Output               
    

    Sample:

    function test {
        Write-Host calc
        return 11
    }
    
    $t = test
    "Objects returned: $($t.count)"
    $t
    
    #Output
    calc
    Objects returned: 1
    11
    

    Also, if you return the value on the last line in your function, then you don't need to use return. Writing the Object/value by itself is enough.

    function test {
        Write-Host calc
        11
    }
    

    The difference is that return 11 would skip the lines after it you use it in the middle of a function.

    function test {
        return 11
        12
    }
    
    test
    
    #Output
    11
    

提交回复
热议问题