Powershell - 如何从当前会话中获取所有文本输出作为字符串?

Powershell - How to get all the text output from current session as a string?

我有一个运行许多命令的长脚本。这些命令通过标准输出和标准错误将文本打印到屏幕上。我想在脚本末尾添加一些逻辑,将所有文本打印到屏幕(标准输出或标准错误)并将其保存到文本文件。

但是,我想要将标准输出和标准错误重定向到文本文件,因为我希望脚本的用户能够看到所有打印的文本在脚本运行时实时显示到屏幕上。实际上,在脚本的某些位置,某些命令可能会要求用户输入。相反,我希望能够 "GetScreenContentsText()" 然后将其输出写入屏幕。

有没有办法在 PowerShell 中执行此操作?

正如 Mathias 在评论中指出的那样,Start-Transcript cmdlet (followed by a matching Stop-Transcript 调用)通常是 创建会话记录.[=25= 的正确工具]

但是,Start-Transcript 并未捕获 所有内容,并且存在 一般问题和限制(写于 PowerShell [Core ] 7.0):

  • 互动提示 (Read-Host, [Console]::ReadLine()) 不是 转录 - 你既不会看到提示字符串,也不会看到用户输入的内容。

  • 甚至 output 也可能在某些情况下从转录本中丢失,如 GitHub issue #10994 中所述。 =25=]

  • 错误消息可以被转录两次并且使用转录可以改变脚本的行为 - 参见 GitHub issue #4645.

  • VT 序列(ANSI 转义码) 捕获,因此控制台中显示的任何颜色都将丢失.

前两个关联的 GitHub 问题提示以下 response from the PowerShell committee,反映了 PowerShell 7.0 的现状(强调已添加):

@PowerShell/powershell-committee reviewed this, we believe a complete solution for transcription (like the unix `script command) [is called for;] would love to see the community build a new cmdlet (published to PSGallery) that uses ptty or on Windows grabbing the screen buffer, but the ask is out of scope for the current transcription framework.

说到类 Unix 平台上的 script utility:虽然它通常是 Start-Transcript 的更好替代品(尽管并非设计用于 内部 脚本),PowerShell 的 PSReadLine 模块,也用于通过 Read-Host 提示用户,不适合它。


至于可能的解决方法:不幸的是,听起来您必须在脚本的输出中手动复制提示字符串和用户输入,以便在脚本中捕获它们 - if修改脚本是一种选择。