启动进程并将输出重定向到$null

8

我这样开始一个新的进程:

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

if ($p.ExitCode -ne 0)
{
    Write-Host = "Failed..."
    return
}

我的可执行文件在控制台上输出了很多内容。有没有办法不显示来自我的exe的输出?
我尝试添加 -RedirectStandardOutput $null 标志,但它不起作用,因为 RedirectStandardOutput 不接受 null。我还尝试将 | Out-Null 添加到 Start-Process 函数调用中,但也没有起作用。是否有可能隐藏我在 Start-Process 中调用的exe的输出?

你可以在脚本顶部尝试使用 $ErrorActionPreference = 'silentlycontinue'。 - Owain Esau
2个回答

12
使用调用运算符&| Out-Null是更受欢迎的选项,但是可以从Start-Process中丢弃标准输出。
显然,在Windows中NUL似乎是任何文件夹中的虚拟路径-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

-RedirectStandardOutput "NUL" 也可以起作用。


9
您正在同步地调用可执行文件(-Wait)并在同一窗口中(-NoNewWindow)运行。
对于这种类型的执行你根本不需要使用Start-Process - 只需直接调用可执行文件,使用调用操作符&,它允许您:
- 使用标准重定向技术来消除(或捕获)输出 - 检查自动变量$LASTEXITCODE的退出代码
& $pathToExe $argumentList *> $null
if ($LASTEXITCODE -ne 0) {
  Write-Warning "Failed..."
  return
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接