Clear captured output/return value in a Powershell function

前端 未结 8 678
灰色年华
灰色年华 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:10

    I ran into the same issue. In PS a function would return all output pipe information. It gets tricky to | Out-Null rest of the code in the function. I worked around this by passing return variable as a reference parameter [ref] . This works consistently. Check the sample code below. Note: some of the syntax is important to avoid errors. e.g. parameter has to be passed in brackets ([ref]$result)

    function DoSomethingWithFile( [ref]$result, [string]$file )
    {
        # Other code writing to output
        # ....
    
        # Initialize result
        if (Test-Path $file){
            $result.value = $true
        } else {
            $result.value = $false
        }
    }
    $result = $null
    DoSomethingWithFile ([ref]$result) "C:\test.txt" 
    

提交回复
热议问题