Skip to content

Instantly share code, notes, and snippets.

@adbertram
Created May 14, 2019 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adbertram/4e4bf0ba5f876ed474f90534520cf2e2 to your computer and use it in GitHub Desktop.
Save adbertram/4e4bf0ba5f876ed474f90534520cf2e2 to your computer and use it in GitHub Desktop.
function Save-ConsoleOutputToClipBoard {
[OutputType('string')]
[CmdletBinding()]
param
()
if ($host.Name -ne ‘ConsoleHost’) {
write-host -ForegroundColor Red "This script runs only in the console host. You cannot run this script in $($host.Name)."
}
# Initialize string builder.
$textBuilder = new-object system.text.stringbuilder
# Grab the console screen buffer contents using the Host console API.
$bufferWidth = $host.ui.rawui.BufferSize.Width
$bufferHeight = $host.ui.rawui.CursorPosition.Y
$rec = new-object System.Management.Automation.Host.Rectangle 0, 0, ($bufferWidth – 1), $bufferHeight
$buffer = $host.ui.rawui.GetBufferContents($rec)
# Iterate through the lines in the console buffer.
for($i = 0; $i -lt $bufferHeight; $i++) {
for($j = 0; $j -lt $bufferWidth; $j++) {
$cell = $buffer[$i, $j]
$null = $textBuilder.Append($cell.Character)
}
$null = $textBuilder.Append("`r`n")
}
## Ensure the PS prompt is always just PS>
$out = $textBuilder.ToString() -replace 'PS .*\>', 'PS>'
## Remove the line that actually invoked this function
$out -replace "PS> $($MyInvocation.MyCommand.Name)" | Set-Clipboard
}
@ToddKlindt
Copy link

I like it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment