Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

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

I have some helper functions that write to STDOUT for logging purposes. Some of these functions return a value to the caller, but the entire output from the function is returned.

How can I have my functions write to STDOUT and return a value to the caller without the return value being polluted with all the STDOUT emitted during the function call?

I'm looking for some kind of design pattern or best practise.

Consider this script:

Function a
{
    Write-Output "In Function a"
    $a = 4
    return $a   
}

$b = a

Write-Output "Outside function: `$b is $b"

The output is

Outside function: $b is In Function a 4

But I want the output to be:

In Function a
$b is 4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

In 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 or one of the other ouptput streams (depending on the type of output you want to create):

    Function a {
      Write-Host 'some text'
      Write-Verbose 'verbose message'
      Write-Information 'info message'   # requires PowerShell v5 or newer
      $a = 4
      return $a
    }
    

    Side note: Write-Information is not available prior to PowerShell v5 when the information stream was introduced, and starting with that version Write-Host also writes to that stream rather than directly to the host console.

  • capture the output in a variable or "assign" it to $null:

    Function a {
      $var = Write-Output 'some text'
      $null = 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
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...