windowspowershellwindows-server-2016

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?


Solution

  • 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 (current as of PowerShell (Core) 7 v7.5.x):

    The first of the linked GitHub issues prompted the following response from the PowerShell committee, which reflects the status quo as of PowerShell 7.5.x (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:


    As for possible workarounds: