我在powershell中写了一个脚本来运行批处理文件并将stderror和stdout保存到文件中(stdout: stdout.txt ; stderr: stderr.txt 并合并了stdout和stderr: AllOutput.txt

test.ps1:

$allOutput =  & C:\foo.bat 2>&1
$stderr = $allOutput | ?{ $_ -is [System.Management.Automation.ErrorRecord] }
$stdout = $allOutput | ?{ $_ -isnot [System.Management.Automation.ErrorRecord] }

Write-Host $allOutput

$allOutput | Out-File AllOutput.txt
$stdout | Out-File StdOut.txt
$stderr | Out-File StdErr.txt

foo.bat 文件执行一些代码和bar.bat脚本:

dir
echo test
c:\bar.bat
echo endFoo

bar.bat 文件执行此exaple代码:

echo test
cd DDDDDD #not exists to get error
cd EEEEEE #not exists to get error
echo endBar

当我直接在服务器上运行test.ps1时,我得到 AllOutput.txt 正确的顺序 - 当在stderr上是一个错误我在命令后得到它 . 但是当我通过 Invoke-Command -computerName serverName -File C:\test.ps1Invoke-Command -computerName serverNAme -File \\serverPath\test3.ps1 在远程服务器上启动时,我输出的顺序错误 - 有时连续两次出现stderr错误,有时是文件末尾的错误 . 如何执行或以正确的方式重写?