gpt4 book ai didi

powershell - RedirectStandardError $logFile 并 append ?

转载 作者:行者123 更新时间:2023-12-02 23:07:05 26 4
gpt4 key购买 nike

我有一个 PowerShell 脚本,我在其中使用 Start-Process 并将输出重定向到日志文件。 cmd 处于 for 循环中,我希望每次运行时都 append 输出。现在它每次运行时都会清除日志文件。有没有办法重定向和追加?

Start-Process $cmd -ArgumentList $cmdArgs -RedirectStandardError $logFile -Wait -NoNewWindow

最佳答案

注意:同步执行控制台应用程序,请直接调用它们(c:\path\to\some .exe ...& $exePath ...),请勿使用 Start-Process -请参阅this answer ;这样,您可以使用 $ouput = c:\path\to\some.exe ... 直接捕获它们的输出,或者使用 >> 将它们的输出 append 到现有文件中 或通过管道传输到 Add-Content[1] - 请参阅 about_Redirection

  • 将重定向 2>&1>> $logFile 结合使用,捕获标准错误输出以及标准输出。<
& $cmd $cmdArgs 2>&1 >> $logFile
  • 使用重定向 2>> $logFile 来捕获标准错误输出。
& $cmd $cmdArgs 2>> $logFile

此答案的其余部分解决了所提出的问题:


不,(从 PowerShell 7.0 开始)无法使用 Start-Process append 到预先存在的文件。 '
-RedirectStandardOutput-RedirectStandardError 参数
- 它们总是替换指定的输出文件。

This answer展示了如何直接使用底层 .NET API,允许您在内存中收集进程的输出,然后允许您将其 append 到现有文件(例如,使用
Add-Content )。

但是,如 your own answer显示,使用辅助临时文件
-RedirectStandardError,其内容稍后 append 到整个输出文件可能是最简单的解决方案。


[1] >> 盲目应用 Out-File 的默认编码,即 Windows 中的 UTF-16LE(“Unicode”) PowerShell,以及 PowerShell [Core] 6+ 中的无 BOM UTF-8;相比之下,Add-Content 会尝试匹配目标文件预先存在的编码。

关于powershell - RedirectStandardError $logFile 并 append ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60907656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com