使用启动进程和管道输出文件到文本文件的 Powershell 脚本不起作用,生成空白文本文件

Powershell script using start-process and piping out-file to text file, not working, produces blank text file

这是我关于 SO 的第一个问题,所以开始吧!

我开始使用一个简单的 powershell 脚本,我打算用它来对某些归档软件进行基准测试。 我想 运行 存档器(在本例中为 Windows 10 上的 7-zip)并将控制台输出写入文本文件以作为日志保存。 然后,我想将开始时间、结束时间、文件大小等附加到同一个日志中。

问题是我无法将输出发送到文本文件。 在多次尝试中,我永远无法让它发挥作用。 我尝试了 Out-File 和正常的“>”重定向,但它仍然以空结尾。 我什至尝试在 Start-Process 上设置 -PassThru 参数,但它只发送对象属性而不是主机内容。

奇怪的是,当我在带有“>”重定向的 CMD 中执行此命令 运行 时,它按预期工作并且我找到了一个包含预期内容的文本文件。

这是我当前的 powershell 脚本:

zFilePath = "C:\Program Files-Zipz.exe"
$dateStart = Get-Date
$contentsToArchive = "D:\Temp -Local\Attack on Titan- Before the Fall-002.jpg"
$workingFolder = "D:\Temp"
$archiveName = "testing {0:yyyy-MM-dd hh.mm.ss.ffff}" -f ($dateStart)
$argument = "a -t7z -m0=LZMA2 -mmt=on -mx9 -md=64m -ms=16g -mfb=273 -mqs=on -mtc=on -mta=on -bb3 `"$workingFolder$archiveName.7z`" `"$contentsToArchive`""
Set-Location $workingFolder
Start-Process -FilePath zFilePath -NoNewWindow -ArgumentList $argument | Out-File ".$archiveName.txt"

我正在回答我自己的问题,因为 Santiago Squarzon and mklement0 已经在我的 OP 的评论中提出了解决方案。

Santiago 允许我使用 Start-Process:

生成结果
zFilePath = "C:\Program Files-Zipz.exe"
$contentsToArchive = "D:\Temp -Local\Attack on Titan- Before the Fall-002.jpg"
$workingFolder = "D:\Games\Emulation\ROMS\GoodGen V3.21"
$archiveName = "testing {0:yyyy-MM-dd HH.mm.ss.ffff}" -f ($dateStart)

$argument = "a -t7z -m0=LZMA2 -mmt=on -mx9 -md=64m -ms=16g -mfb=273 -mqs=on -mtc=on -mta=on -bb3 `"$workingFolder$archiveName.7z`" `"$contentsToArchive`""
Set-Location $workingFolder
Start-Process zFilePath "$argument" -NoNewWindow -Wait -RedirectStandardOutput ".$archiveName.txt"

基本上,要使用 Start-Process 并生成一个文本文件,我需要在 -RedirectStandardOutput 参数(我没有使用)中指定它的输出。

但是,输出没有显示在主机中,因为它直接转到指定的文本文件。

为此,mklement0 的解释和 wiki 非常有用。使用 & 调用要好得多:

& zFilePath `"$argument`" | Out-File -FilePath ".$archiveName.txt"

有了这个,我在主机中得到了输出,并且它也被复制到文本文件中。

非常感谢你们。