Creating Colorful Console Hardcopies

by Feb 26, 2020

If you’d like to hardcopy the content of a PowerShell console, you can copy and select the text, but this messes up colors and formatting.

A better way is reading the console screen buffer, and composing HTML documents. These HTML documents can then be copied and pasted into Word and other targets, and keep formatting and colors

The code below is certainly not yet perfect but illustrates the path to take:

function Get-ConsoleBufferAsHtml
  $html = [Text.StringBuilder]''
  $null = $html.Append("<pre style='MARGIN: 0in 10pt 0
  font-size:10 >")
  $bufferWidth = $host.UI.RawUI.BufferSize.Width
  $bufferHeight = $host.UI.RawUI.CursorPosition.Y

  $rec = [Management.Automation.Host.Rectangle]::new(
    0,0,($bufferWidth - 1),$bufferHeight
  $buffer = $host.ui.rawui.GetBufferContents($rec)

  for($i = 0 $i -lt $bufferHeight $i++)
    $span = [Text.StringBuilder]''
    $foreColor = $buffer[$i, 0].Foregroundcolor
    $backColor = $buffer[$i, 0].Backgroundcolor
    for($j = 0 $j -lt $bufferWidth $j++)
      $cell = $buffer[$i,$j]
      if (($cell.ForegroundColor -ne $foreColor) -or ($cell.BackgroundColor -ne $backColor))
        $null = $html.Append(
"<span style='color:$foreColor;background:$backColor'>$($span)</span>"
        $span = [Text.StringBuilder]''
        $foreColor = $cell.Foregroundcolor
        $backColor = $cell.Backgroundcolor
      $null = $span.Append([Web.HttpUtility]::HtmlEncode($cell.Character))

    $null = $html.Append(
"<span style='color:$foreColor;background:$backColor'>$($span)</span><br/>"

  $null = $html.Append("</pre>")

Note that this function requires a true console window, so it won’t work in the PowerShell ISE. When you run the code above, it provides you with a new command called Get-ConsoleBufferAsHtml.

To hard-copy the current console content to a HTML file, run this:

PS>  Get-ConsoleBufferAsHtml | Set-Content $env:temp\test.html   

To open the generated HTML in your associated browser, run this:

PS>  Invoke-Item $env:temp\test.html  

You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: (June 2-5, 2020 in Hanover, Germany).

It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.

Secure your seat while they last: The speakers and agenda is available here: The speakers and agenda is available here:

Twitter This Tip! ReTweet this Tip!