我有一个函数,在该功能中,我正在调用一个git函数:
function Confirm-GitStatus
{
# a bunch of stuff
& git --git-dir $gitDir --work-tree $basePath checkout $targetBranch 2>&1
# more stuff
return $true
}
实际上是一个数组,其中包含git调用和$ true的结果。为了获得我想要的结果,我必须这样做:
$disposableMessage = & git --git-dir $gitDir --work-tree $basePath checkout $targetBranch 2>&1
这感觉很粗糙。拨打电话和扔结果的最佳做法是什么?
因为您正在使用流重定向 - 2>&1
将PowerShell错误流合并(从git
的STDERR)与成功流(从STDOUT)合并) - 最简单的解决方案是 redirect all 流( *
)to $null
to *> $null
;一个简化的示例:
# Note: This command produces both stdout and stderr output.
cmd /c "echo hi & dir nosuch" *> $null
# PowerShell Core example with Bash:
bash -c 'echo hi; ls nosuch' *> $null
然而,一般考虑丢弃命令(成功)输出的$null = ...
,因为它:
在前
传达意图在大多数情况下都比
> $null
(尤其是... | Out-Null
)都快。
应用于上面的示例:
$null = cmd /c "echo hi & dir nosuch" 2>&1
$null = bash -c 'echo hi; ls nosuch' 2>&1
[1]在powershell(core)6 中,Out-Null
具有优化,如果前面的管道段是 side forme-forme-fime-fime-fime-fim-fim-fim-em>,而不是方法或命令调用;例如,1..1e6 | Out-Null
几乎没有时间执行,因为该表达式似乎没有执行。但是,这种情况是非典型的,功能等效的 Write-Output (1..1e6) | Out-Null
运行时间比$null = Write-Output (1..1e6)
长得多。
您可以将命令输送到Out-Null
。