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

前端 未结 10 909
暖寄归人
暖寄归人 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 02:11

    PowerShell does pipes awkwardkly. To work around the return value problem and save the pipeline for real data, pass the function a value by reference, that is, an array. The array can be loaded with the value you wish to return. Here's a simple example:

    # tp.ps1
    #   test passed parameters
    #   show that arrays are passed by reference, and can be used to provide
    #   return values outside the pipeline
    function doprint
    {
        process { write-output "value now: $psitem" }
    }
    
    function recurse($thing,     $rtx)
    {
        $thing++
        if($thing -lt 20) {
            if($thing -eq 15) { $rtx[0] = $thing }
            write-output $thing | doprint
            recurse $thing     $rtx
        }
    }
    
    j=0
    $rtv=@(4)
    recurse $j     $rtv
    write-output $rtv[0]
    

提交回复
热议问题