Yesterday on Facebook, Ed Wilson was lamenting about confusion of keyboard shortcuts between PowerShell and Microsoft Word. I've run into the same issue. Muscle memory is strong. Then the discussion turned to getting content from the PowerShell ISE into a Word document. I humorously suggested we had a plugin and it had a Ctrl+C keyboard shortcut. Then I thought, why not make this even easier!
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
So I put together a quick function for the PowerShell ISE.
Function Send-ToWord { [cmdletbinding()] Param( [ValidatePattern("\S+")] [string[]]$Text = $psise.CurrentFile.Editor.SelectedText) If (($global:word.Application -eq $Null) -OR -NOT (Get-Process WinWord)) { #remove any variables that might be left over just to be safe Remove-Variable -Name doc,selection -Force -ErrorAction SilentlyContinue #create a Word instance if the object doesn't already exist $global:word = New-Object -ComObject word.application #create a new document $global:doc = $global:word.Documents.add() #create a selection $global:selection = $global:word.Selection #set font and paragraph for fixed width content $global:selection.Font.Name = "Consolas" $global:selection.font.Size = 10 $global:selection.paragraphFormat.SpaceBefore = 0 $global:selection.paragraphFormat.SpaceAfter = 0 #show the Word document $global:word.Visible = $True } #insert the text $global:selection.TypeText($text) #insert a new paragraph (ENTER) $global:selection.TypeParagraph() } #end Function
This function will paste any selected text from the ISE into a Word document. The first time you run the function, PowerShell will create a Word document and format it for fixed width text. It will then insert your text and a new paragraph marker. The next time you run the function, it should detect that you have a document open and re-use the existing variables. The Word document will be visible so you can edit it further and save it. If you move the cursor around in the document, any new content you insert will go there.
To make this easy to use, insert this function into your PowerShell ISE profile script and add a menu item with a keyboard shortcut.
$psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Send to Word",{Send-ToWord},"Ctrl+Alt+W") | Out-Null
Now, I can select code from the ISE script pane and send it to Word with a quick key combination. Have fun and enjoy your weekend.
Update: I posted another version that includes an option to copy and paste as colored code.