问题
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
回答1:
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
returnkeyword.
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-Informationis not available prior to PowerShell v5 when the information stream was introduced, and starting with that versionWrite-Hostalso 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 }
来源:https://stackoverflow.com/questions/21232024/best-way-to-return-values-from-a-function-that-writes-to-stdout