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

前端 未结 10 879
暖寄归人
暖寄归人 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条回答
  •  -上瘾入骨i
    2020-12-24 02:13

    @Michael Sorens's answer is useful, but it suggests a design strategy that seems rather onerous. I don't want to have to separate out data processing functions from functions that report progress or diagnostic messages. Reading his blogpost, I found a less hacky work-around to the OP's question. Here's the key sentence from the blog post:

    A PowerShell function returns all uncaptured output.

    So what if we capture our output?

    function Calculate
    {
       $junkOutput = echo "Calculate"
       return 11
    }
    
    $result = Calculate
    

    Now $result just contains 11, as intended.

提交回复
热议问题