PowerShell:运行 批处理文件并将输出写入文本文件

PowerShell: Run batch file and write output to text file

我的 PowerShell 脚本中有一个批处理文件,我想 运行 并将其输出写入文本文件。我尝试了以下方法:

Start-Process C:\path\file.bat | Out-File C:\path\output.txt

我也试过使用 Tee-Object and Write-Output in place of Out-File,但没有任何内容写入文本文件。

您可以使用 Start-Transcript and Stop-Transcript 让 PowerShell 控制台将所有控制台输出写入文本文件。

这样使用:

Start-Transcript -Path C:\temp\log.txt
&C:\path\file.bat
Stop-Transcript

有关详细信息,请参阅 the documentation

如果你想要bat文件的输出,例如构建脚本的结果,然后我发现以下效果最好:

$Product = 'ProductName' 
&C:\Path$Product.bat | Out-File C:\Path$Product-Output.txt

您只需要几个参数:

Start-Process -FilePath 'C:\Path\File.bat' -RedirectStandardOutput 'C:\Path\Output.txt' -Wait -WindowStyle Hidden

-RedirectStandardOutput 将输出发送到您的文本文件,-Wait 等待批处理文件完成,-WindowStyle Hidden 隐藏用于批处理文件的 window .