简体   繁体   中英

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

I have a long script that runs many commands. These commands print text to the screen via standard output and standard error. I want to add some logic at the end of the script that takes all text printed to the screen (standard out or standard error) and saves it to a text file.

However, I do not want to redirect standard output and standard error to a text file because I want the user of the script to be able to see all the text getting printed to the screen in real time as the script runs. Indeed, at some points in the script, some of the commands may ask for user input. Instead, I want to be able to "GetScreenContentsText()" and then write the output of this to the screen.

Is there a way to do this in PowerShell?

As Mathias points out in a comment, the Start-Transcript cmdlet (followed by a matching Stop-Transcript call) is generally the right tool for creating session transcripts .

However, Start-Transcript doesn't capture everything and has general problems and limitations (written as of PowerShell [Core] 7.0):

  • Interactive prompts ( Read-Host , [Console]::ReadLine() ) are not transcribed - you'll see neither the prompt string nor what the user typed.

  • Even output can situationally be missing from the transcript, as discussed in this GitHub issue .

  • Error messages can be transcribed twice and using transcription can change the script's behavior - see this GitHub issue .

  • VT sequences (ANSI escape codes) are not captured , so any coloring shown in the console is lost.

The former of the two linked GitHub issues prompted the following response from the PowerShell committee , which reflects the status quo as of PowerShell 7.0 (emphasis added):

@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.

Speaking of the script utility on Unix-like platforms: while it is a superior alternative to Start-Transcript in general there (though not designed to be used from inside scripts), PowerShell's PSReadLine module, which is also used for prompting users via Read-Host , doesn't play nice with it.


As for a possible workaround: Unfortunately, it sounds like you'll have to manually duplicate prompt strings and user input in your script's output in order for them to be captured in the transcript - if modifying the script is an option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM