Clear captured output/return value in a Powershell function

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

    Using the information from user1654962, here is the way that I worked around this PowerShell issue. Since, if there is output information, PowerShell will return it as an array, I decided to make sure the function output was always an array. Then the calling line can use [-1] to get the last element of the array and we'll get a consistent return value.

    function DoSomething()
    {
      # Code that could create output
      Write-Output "Random output that we don't need to return"
      Write-Output "More random output"
    
      # Create the return value. It can be a string, object, etc.
      $MyReturnString = "ImportantValue"
    
      # Other code
    
      # Make sure the return value is an array by preceding it with a comma
      return ,$MyReturnString
    }
    
    $CleanReturnValue = ( DoSomething() )[-1]
    

提交回复
热议问题