Best way to return values from a function that writes to STDOUT

有些话、适合烂在心里 提交于 2019-11-27 16:14:29

In PowerShell all non-captured output inside a function is returned, not just the argument of return. From the documentation:

In Windows PowerShell®, the results of each statement are returned as output, even without a statement that contains the Return keyword.

It doesn't matter if the function looks like this:

function Foo {
  'foo'
}

or like this:

function Foo {
  'foo'
  return
}

or like this:

function Foo {
  return 'foo'
}

it will return the string foo either way.

To prevent output from being returned, you can

  • write to the host:

    Function a {
      Write-Host 'some text'
      $a = 4
      return $a
    }
    
  • capture the output in a variable:

    Function a {
      $var = Write-Output 'some text'
      $a = 4
      return $a
    }
    
  • or redirect the output to $null:

    Function a {
      Write-Output 'some text' | Out-Null
      Write-Output 'some text' >$null
      $a = 4
      return $a
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!