Sometimes I want to copy a command from Powershell to paste in a document, or I want to copy the output? How can I select and copy text in Powershell?
At least I know a way how to paste a text (or a command) into Powershell: you just right-click on Powershell.
27 Answers
Just select the text in the console window and press enter or the right mouse button. That selected text ends up in your clipboard.
Note that this will only work if QuickEdit mode is enabled for the console window. If it is not, then either enable it in the console window properties (System menu → Properties → Options) or enter Mark mode via System menu → Edit → Mark (Alt+Space, E, K on an English Windows).
2Or send the output of your command directly to clipboard using clip.exe For example,
Get-ChildItem C:\Test -recurse | Clip 7 Go to the menubar, top left, Edit, Select All, Copy, paste in notepad
1Have a look at Send Text in Clipboard to Application like Notepad (C# or Powershell). You will find some more tips. However, answer by @Wictor is probably the easiest solution.
I've build my own out-clipboard funciton for this.
Function Out-Clipboard{ param($Value,[switch]$PassThru) begin { [void][reflection.assembly]::LoadWithPartialName("Windows.Forms") $tb = New-Object System.Windows.Forms.TextBox $tb.Multiline = $true $pipeObjects = @() } process { $pipeObjects+=$_ } end { if([string]::IsNullOrEmpty($Value)){ $text=$null $pipeObjects | out-string -stream | %{$text = $text + $(if($text -ne $null){"`r`n"}) + $_} $tb.text = $text } else { $tb.text = $value } $tb.SelectAll() $tb.Copy() if($PassThru){ $pipeObjects } $tb.Dispose() }
}Sample command line:
Get-Process | Out-ClipboardHope it's what you're looking for.
3Set-Clipboard is standard cmdlet as of Powershell v5.0. In some cases you should convert objects to text with Out-String before piping result to the clipboard:
Get-ChildItem C:\Windows -recurse -depth 1 | Out-String -stream | Set-Clipboard If you want to copy the last command you typed to the clipboard, the following command is useful (especially for commands that span multiple lines):
(Get-History -Count 1).CommandLine | Set-ClipboardIf you want to repeat the last command, and copy its output to the clipboard, use:
Invoke-History | Set-ClipboardCaveat: you should only do this for inexpensive and idempotent commands without any side-effects.