Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...