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
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 }
来源:https://stackoverflow.com/questions/21232024/best-way-to-return-values-from-a-function-that-writes-to-stdout