PowerShell:在函数内处理调用结果 - 最佳实践 [英] PowerShell: Disposing of a call result within a function - best practice
问题描述
我有一个函数,在该函数中,我调用了一个 git 函数:
I have a function, and within that function, I am calling a git function:
function Confirm-GitStatus
{
# a bunch of stuff
& git --git-dir $gitDir --work-tree $basePath checkout $targetBranch 2>&1
# more stuff
return $true
}
这个结果实际上是一个包含 git 调用结果和 $true 的数组.为了得到我想要的结果,我不得不这样做:
The result of this is actually an array containing the result of the the git call and $true. In order to get the result I wanted, I had to do this:
$disposableMessage = & git --git-dir $gitDir --work-tree $basePath checkout $targetBranch 2>&1
这感觉很恶心.拨打电话并抛出结果的最佳做法是什么?
This feels gross. What is the best practice for making calls and tossing the result?
推荐答案
由于您无论如何都在使用流重定向 - 2>&1
来合并 PowerShell错误流(从git
的stderr)到成功流(从stdout))——最简单的解决方案是重定向所有流(*
) 到 $null
和 *>$null
;一个简化的例子:
Since you're using a stream redirection anyway - 2>&1
to merge the PowerShell error stream (from git
's stderr) to the success stream (from stdout)) - the simplest solution is to redirect all streams (*
) to $null
with *> $null
; a simplified example:
# 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 = ...
丢弃命令的(成功)输出,因为它:
However, in general consider $null = ...
for discarding a command's (success) output, because it:
传达意图预先
比 > 都快$null
尤其是 ... |大多数情况下为 Out-Null
.[1]
应用于以上示例:
$null = cmd /c "echo hi & dir \nosuch" 2>&1
$null = bash -c 'echo hi; ls \nosuch' 2>&1
[1] 在 PowerShell (Core) 6+ 中,Out-Null
有一个优化,如果前面的管道段是一个无副作用的表达式而不是方法或命令调用;例如,1..1e6 |Out-Null
几乎立即执行,因为该表达式似乎甚至没有执行.然而,这种情况是非典型的,功能上等效的 Write-Output (1..1e6) |Out-Null
需要很长时间才能运行,远比 $null = Write-Output (1..1e6)
长.
[1] In PowerShell (Core) 6+, Out-Null
has an optimization if the only preceding pipeline segment is a side effect-free expression rather than a method or command call; e.g., 1..1e6 | Out-Null
executes in almost no time, because the expression is seemingly not even executed. However, such a scenario is atypical, and the functionally equivalent Write-Output (1..1e6) | Out-Null
takes a long time to run, much longer than $null = Write-Output (1..1e6)
.
这篇关于PowerShell:在函数内处理调用结果 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!