Clear captured output/return value in a Powershell function

前端 未结 8 614
灰色年华
灰色年华 2021-01-01 23:33

Is there a way to clear the return values inside of a function so I can guarantee that the return value is what I intend? Or maybe turn off this behaviour for the function?<

相关标签:
8条回答
  • 2021-01-02 00:24

    This is one that caused me some trouble with much larger functions.

    One can take the first answer "Pipe output to Out-Null" a bit further. We take the code in our function and embed this in a script block, which we then pipe its output to Out-Null.

    Now we don't need to trawl through all the code in the function...like so:

    function GetArray() 
    {
        .{
            # $AutoOutputCapture = "Off" ?
            $myArray = New-Object System.Collections.ArrayList
            $myArray.Add("Hello")
            $myArray.Add("World")
    
        } | Out-Null
    
        # Clear return value before returning exactly what I want?
        return $myArray
    }
    
    $x = GetArray
    $x
    
    0 讨论(0)
  • 2021-01-02 00:24

    Set variable scope to script or global.

    function Get-Greeting {
        'Hello Everyone'
        $greeting = 'Hello World'
        'Ladies and Gentlemen'
        $script:greeting = $greeting
    }
    
    Get-Greeting
    $greeting <== 'Hello World'
    
    0 讨论(0)
提交回复
热议问题