我有一些辅助函数可以写入 STDOUT 以进行记录。其中一些函数会向调用者返回一个值,但会返回函数的整个输出。
如何让我的函数写入 STDOUT 并将值返回给调用者,而返回值不会被函数调用期间发出的所有 STDOUT 污染?
我正在寻找某种设计模式或最佳实践。
考虑这个脚本:
Function a
{
Write-Output "In Function a"
$a = 4
return $a
}
$b = a
Write-Output "Outside function: `$b is $b"
输出是
Outside function: $b is In Function a 4
但我希望输出是:
In Function a
$b is 4
最佳答案
在 PowerShell 中,返回函数内所有未捕获的输出,而不仅仅是 return
的参数。 .来自 documentation :
In PowerShell, the results of each statement are returned as output, even without a statement that contains the
return
keyword.
函数看起来像这样并不重要:
function Foo {
'foo'
}
或者像这样:
function Foo {
'foo'
return
}
或者像这样:
function Foo {
return 'foo'
}
它将返回字符串
foo
无论哪种方式。为防止返回输出,您可以
Function a {
Write-Host 'some text'
Write-Verbose 'verbose message'
Write-Information 'info message' # requires PowerShell v5 or newer
$a = 4
return $a
}
旁注:
Write-Information
当 information stream 时,在 PowerShell v5 之前不可用被引入,并从该版本开始 Write-Host
也写入该流而不是直接写入主机控制台。 $null
:Function a {
$var = Write-Output 'some text'
$null = Write-Output 'some text'
$a = 4
return $a
}
$null
:Function a {
Write-Output 'some text' | Out-Null
Write-Output 'some text' >$null
$a = 4
return $a
}
关于function - 从写入 STDOUT 的函数返回值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21232024/