在 PowerShell 中禁止 Git 命令的输出

7 git powershell io-redirection

作为我正在运行的脚本的一部分git clean -fd。它通常会输出一堆已清理的文件。我想抑制这个输出。

我尝试过git clean -fd | Out-Null,但似乎不起作用。git谷歌搜索没有返回抑制输出的选项,那么我可以使用另一种 PowerShell 方法吗?或者我做错了什么?值得注意的是,PowerShell 脚本本身是从.bat文件中执行的。

mkl*_*nt0 8

博士的有用答案为当前的案例提供了最佳解决方案。

至于为什么... | Out-Null没有效果:

Out-Null仅抑制来自外部程序(例如 )的stdoutgit输出,但不抑制stderr输出。

git与许多 CLI(控制台/终端程序)一样,使用 stderr 流不仅用于报告错误,还用于状态信息- 基本上是非数据的任何信息。

要抑制stdout和 stderr 输出,请使用*> $null

git clean -fd *> $null
Run Code Online (Sandbox Code Playgroud)

注意:*> $null抑制所有输出流;虽然外部程序只有2 个(stdout 和 stderr),但应用*>$nullPowerShell 本机命令会静默所有 6 个输出流。

有关详细信息,请参阅about_Redirection 。


可选阅读:来自外部程序的选择性流重定向:

根据nmbell的反馈:

  • >$null(或1>$null) 可用于选择性地抑制stdout输出,这实际上与 相同。| Out-Null

  • 2>$null可用于选择性地抑制stderr输出。

  • *>$null如上所述,使两个(所有)流静音。

当然,$null重定向目标也可以是文件(名称或路径),而不是抑制输出。

笔记:

  • PowerShell 在其管道中逐行处理来自外部程序的输出如果输出在变量( $out = ...) 中捕获并且包含2 行或更多行,则将其存储为行(字符串)数组( [object[]])。

  • 在发送和接收数据时,PowerShell 仅与外部程序“讲文本”(使用字符串),这意味着可能会出现字符编码问题。

  • 有关这两个方面的更多信息,请参阅此答案。


场景示例

设置:

git clean -fd *> $null
Run Code Online (Sandbox Code Playgroud)

捕获标准输出,通过以下方式传递标准错误:

PS> $captured = & $externalCmd; "Captured: $captured"
err            # Stderr output was *passed through*
Captured: out  # Captured stdout output.
Run Code Online (Sandbox Code Playgroud)

捕获标准输出,抑制标准错误输出,使用2>$null

PS> $captured = & $externalCmd 2>$null; "Captured: $captured"
Captured: out  # Captured stdout output - stderr output was suppressed.
Run Code Online (Sandbox Code Playgroud)

捕获stdout和 stderr,使用*>&1

PS> $captured = & $externalCmd *>&1 | % ToString; "Captured: $captured"
Captured: out err  # *Combined* stdout and stderr output.
Run Code Online (Sandbox Code Playgroud)

笔记:

  • % ToString是 的缩写ForEach-Object ToString,它在每个输出对象上调用该.ToString()方法,这确保System.Management.Automation.ErrorRecordPowerShell 包装stderr行的实例被转换回字符串
  • $captured接收一个 2 元素行数组( [object[]]) - 分别包含 stdout 和 stderr 行作为元素;在本例中,PowerShell 的字符串插值将它们转换为单行、以空格分隔的字符串。

捕获stderr ,抑制 stdout:

PS> $captured = 
      & $externalCmd *>&1 | 
        ? { $_ -is [System.Management.Automation.ErrorRecord] } | 
          % ToString; "Captured: $captured"
Captured: err  # Captured stderr output *only*.
Run Code Online (Sandbox Code Playgroud)

笔记:

  • ? { $_ -is [System.Management.Automation.ErrorRecord] }是 的缩写
    Where-Object { $_ -is [System.Management.Automation.ErrorRecord] },它仅传递 stderr 行(可通过正在测试的包装器类型识别)通过,并% ToString再次将它们转换回字符串。

  • 这种技术既不明显也不方便;GitHub 建议 #4332提出了一种语法,例如2> variable:stderr支持将流重定向到变量,例如$stderr在本例中。


phd*_*phd 5

只需添加选项-q

git clean -fdq
Run Code Online (Sandbox Code Playgroud)