Start-Process 重定向输出到 $null

edw*_*win 4 powershell

我正在开始一个这样的新过程:

$p = Start-Process -FilePath $pathToExe -ArgumentList $argumentList -NoNewWindow -PassThru -Wait

if ($p.ExitCode -ne 0)
{
    Write-Host = "Failed..."
    return
}
Run Code Online (Sandbox Code Playgroud)

我的可执行文件打印了很多到控制台。是否可以不显示我的 exe 的输出?

我试图添加 -RedirectStandardOutput $null标志但它没有用,因为RedirectStandardOutput不接受null. 我还尝试添加| Out-NullStart-Process函数调用中 - 没有用。是否可以隐藏我调用的 exe 的输出Start-Process

mkl*_*nt0 7

您正在同步( -Wait) 并在同一窗口( -NoNewWindow) 中调用可执行文件。

你不需要Start-Process为这种执行在所有-简单地调用可执行直接使用&,电话运营商,它允许您:

  • 使用标准重定向技术来静音(或捕获)输出
  • 并检查$LASTEXITCODE退出代码的自动变量
& $pathToExe $argumentList *> $null
if ($LASTEXITCODE -ne 0) {
  Write-Warning "Failed..."
  return
}
Run Code Online (Sandbox Code Playgroud)

如果您仍然想使用Start-Process,请参阅sastanin 的有用答案


sas*_*nin 6

使用调用运算符&and| Out-Null是一种更流行的选项,但可以丢弃Start-Process.

显然,NUL在 Windows 中似乎是任何文件夹中的虚拟路径-RedirectStandardOutput需要一个非空路径,所以$null参数不被接受,但是"NUL"是(或任何以 结尾的路径\NUL)。

在这个例子中,输出被抑制,文件没有被创建:

> Start-Process -Wait -NoNewWindow ping localhost -RedirectStandardOutput ".\NUL" ; Test-Path ".\NUL"
False
> Start-Process -Wait -NoNewWindow ping localhost -RedirectStandardOutput ".\stdout.txt" ; Test-Path ".\stdout.txt"
True
Run Code Online (Sandbox Code Playgroud)

-RedirectStandardOutput "NUL" 也有效。