【问题标题】:PowerShell: Disposing of a call result within a function - best practicePowerShell:在函数中处理调用结果 - 最佳实践
【发布时间】:2019-03-07 14:50:20
【问题描述】:

我有一个函数,在那个函数中,我正在调用一个 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

这感觉很恶心。拨打电话和折腾结果的最佳做法是什么?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    因为无论如何您都在使用流重定向 - 2>&1 将 PowerShell 错误流(来自 git 的 stderr)合并到成功流(来自 stdout) - 最简单解决方案是所有*)重定向到$null*> $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[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) 长得多。

    【讨论】:

      【解决方案2】:

      您可以通过管道将您的命令发送到Out-Null

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 2012-10-07
        • 1970-01-01
        • 1970-01-01
        • 2011-08-13
        • 1970-01-01
        • 2013-08-23
        相关资源
        最近更新 更多