Print from PowerShell’s Integrated Scripting Environment


Since I started working with the PowerShell V# CTP, I have been using the ISE instead of PowerGUI’s script editor, as PowerGUI does not yet support .Net version 4, which is required by PowerShell V3.

One feature that is missing in the ISE is the ability to print a script.

Jeffry Hicks has a solution at http://jdhitsolutions.com/blog/2011/09/friday-fun-add-a-print-menu-to-the-powershell-ise/, but it uses notepad which in my opinion is severely limited (it’s monochrome, for one thing)

Since I was already copying scripts to colorized html (see previous posts, as well as scripts on powergui.org), I decided to go in another direction.

This script will create an html version of the current script (or current selection) in the ISE or the specified file using an Internet Explorer com object.

The html object includes line numbers.

Once the html is built, and the IE window is opened, you can print using IE’s print functions.

This script is extracted from a module I use to provide basic functions in the ISE that I miss from PowerGUI, or which I had added as script editor add-ons to PowerGui.

This is based on Lee Holmes Set-ClipboardScript located here: http://www.leeholmes.com/blog/2009/02/03/more-powershell-syntax-highlighting/

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
<#
.SYNOPSIS
    Copy-ToPrinter – Prints the current script from the ISE or a file passed the the Path parameter from the console.
.DESCRIPTION
  This script prints a PowerShell script.
.NOTES
    File Name: Copy-ToPrinter.ps1
    Author: Karl Mitschke
    Requires: Powershell V2
    Created: 09/20/2011
.LINK
    “https://unlockpowershell.wordpress.com/2010/PrintFromISE/&#8221;
    “http://gallery.technet.microsoft.com/Script-to-copy-the-c55f0106&#8221;
    “http://www.leeholmes.com/blog/2009/02/03/more-powershell-syntax-highlighting/&#8221;

.INPUTS
Requires a file be open in the ISE, or a file path and name passed to the Path parameter.
.OUTPUTS
    This script outputs a formatted HTML version of the script with line numbers.
.EXAMPLE
    .\Copy-ToPrinter.ps1
    __________
    Prints the contents of the current PowerShell ISE tab.
.EXAMPLE
    .\Copy-ToPrinter.ps1 -Path C:\scripts\Find-EmptyGroups.ps1
    __________
    Prints the contents of the file C:\scripts\Find-EmptyGroups.ps1.
.EXAMPLE
    Get-ChildItem -Path C:\scripts\Find-DisabledMailbox.ps1 | .\Copy-ToPrinter.ps1
    __________
    Prints the contents of the file C:\scripts\Find-DisabledMailbox.ps1.
#>

param(
[Parameter(
Position = 0,
ValueFromPipeline=$true,
Mandatory = $false,
HelpMessage = “The path of the file”
)]
[string] $Path
)
Set-StrictMode -Version 2
$tokenColours = @{
    ‘Attribute’ = ‘DarkCyan’
    ‘Command’ = ‘Blue’
    ‘CommandArgument’ = ‘Magenta’
    ‘CommandParameter’ = ‘DarkBlue’
    ‘Comment’ = ‘DarkGreen’
    ‘GroupEnd’ = ‘Black’
    ‘GroupStart’ = ‘Black’
    ‘Keyword’ = ‘DarkBlue’
    ‘LineContinuation’ = ‘Black’
    ‘LoopLabel’ = ‘DarkBlue’
    ‘Member’ = ‘Black’
    ‘NewLine’ = ‘Black’
    ‘Number’ = ‘Magenta’
    ‘Operator’ = ‘DarkGray’
    ‘Position’ = ‘Black’
    ‘StatementSeparator’ = ‘Black’
    ‘String’ = ‘DarkRed’
    ‘Type’ = ‘DarkCyan’
    ‘Unknown’ = ‘Black’
    ‘Variable’ = ‘Red’
} 
function Append-HtmlSpan ($block, $tokenColor){ 
    if (($tokenColor -eq ‘NewLine’) -or ($tokenColor -eq ‘LineContinuation’)){ 
        if($tokenColor -eq ‘LineContinuation’){ 
            $null = $codeBuilder.Append(‘`’)
        }
        $null = $codeBuilder.Append(“<br />`r`n”) 
        $null = $lineBuilder.Append(“{0:000}<BR />” -f $currentLine) 
$SCRIPT:currentLine++ 
}
    else{
        $block = [System.Web.HttpUtility]::HtmlEncode($block) 
        if (-not $block.Trim()){
            $block = $block.Replace(‘ ‘, ‘&nbsp;’)
        }
        $htmlColor = $tokenColours[$tokenColor].ToString().Replace(‘#FF’, ‘#’)
        if($tokenColor -eq ‘String’ -or $tokenColor -eq ‘Comment’ ){
            $lines = $block -split “`r`n”
            $block = “”
            $multipleLines = $false 
            foreach($line in $lines){ 
                if($multipleLines){
                    $block += “<BR />`r`n”
                    $null = $lineBuilder.Append(“{0:000}<BR />” -f $currentLine)
$SCRIPT:currentLine++
                }
                $newText = $line.TrimStart()
                $newText = “&nbsp;” * ($line.Length  $newText.Length) + $newText
                $block += $newText
                $multipleLines = $true
            }
        }
        $null = $codeBuilder.Append(“<span style=’color:$htmlColor’>$block</span>”)
    }
} 
function GetHtmlClipboardFormat($html, $Caller){
$header = 
@”
Version:1.0
StartHTML:0000000000
EndHTML:0000000000
StartFragment:0000000000
EndFragment:0000000000
StartSelection:0000000000
EndSelection:0000000000
SourceURL:file:///about:blank
<!DOCTYPE HTML PUBLIC `”-//W3C//DTD HTML 4.0 Transitional//EN`”>
<HTML>
<HEAD>
<TITLE>HTML Clipboard</TITLE>
</HEAD>
<BODY>
<!–StartFragment–>
<DIV CLASS=’footerstyle’></DIV>
<DIV style=’font-family:Consolas,Lucida Console; font-size:10pt;
    width:950; border:0px solid black; padding:5px’>

<TABLE BORDER=’0′ cellpadding=’5′ cellspacing=’0′>
<TR>
    <TD VALIGN=’Top’>
<DIV style=’font-family:Consolas,Lucida Console; font-size:10pt;
    padding:5px; background:#cecece’>
__LINES__
</DIV>
    </TD>
    <TD VALIGN=’Top’ NOWRAP=’NOWRAP’>
<DIV style=’font-family:Consolas,Lucida Console; font-size:10pt;
    padding:5px; background:#fcfcfc’>
__HTML__
</DIV>
    </TD>
</TR>
</TBODY>
</TABLE>
</DIV>
<!–EndFragment–>
</BODY>
</HTML>
“@
 
    $header = $header.Replace(“__LINES__”, $lineBuilder.ToString())
    $startFragment = $header.IndexOf(“<!–StartFragment–>”) +
        “<!–StartFragment–>”.Length + 2
    $endFragment = $header.IndexOf(“<!–EndFragment–>”) +
        $html.Length  “__HTML__”.Length
    $startHtml = $header.IndexOf(“<!DOCTYPE”)
    $endHtml = $header.Length + $html.Length  “__HTML__”.Length
    if ($Caller -eq “Print”){
        $header = $header.Replace(“Version:1.0”,“”)
        $header = $header.Replace(“StartHTML:0000000000”,“”)
        $header = $header.Replace(“EndHTML:0000000000”,“”)
        $header = $header.Replace(“StartFragment:0000000000”,“”)
        $header = $header.Replace(“EndFragment:0000000000”,“”)
        $header = $header.Replace(“StartSelection:0000000000”,“”)
        $header = $header.Replace(“EndSelection:0000000000”,“”)
        $header = $header.Replace(“SourceURL:file:///about:blank”,“”)
        #$header = $header.Replace(“HTML Clipboard”, (Split-Path -Path $Path -Leaf))
    }
    else{
        $header = $header -replace “StartHTML:0000000000”, (“StartHTML:{0:0000000000}” -f $startHtml) 
        $header = $header -replace “EndHTML:0000000000”, (“EndHTML:{0:0000000000}” -f $endHtml) 
        $header = $header -replace “StartFragment:0000000000”, (“StartFragment:{0:0000000000}” -f $startFragment) 
        $header = $header -replace “EndFragment:0000000000”, (“EndFragment:{0:0000000000}” -f $endFragment) 
        $header = $header -replace “StartSelection:0000000000”, (“StartSelection:{0:0000000000}” -f $startFragment) 
        $header = $header -replace “EndSelection:0000000000”, (“EndSelection:{0:0000000000}” -f $endFragment) 
    }
    if($Host.Name -eq ‘Windows PowerShell ISE Host’){
        #$header = $header.Replace(“HTML Clipboard”,$psise.CurrentFile.DisplayName)
    }
    $header = $header.Replace(“__HTML__”, $html)
    Write-Verbose $header
    $header
}
function Copy-ToPrinter{

    Add-Type -Assembly PresentationCore
    Add-Type -Assembly System.Web
    $SCRIPT:currentLine = 1
    if($Host.Name -eq ‘Windows PowerShell ISE Host’){
        if ($psise.CurrentFile.Editor.SelectedText.Length -eq 0){
    $text = $psise.CurrentFile.Editor.Text
    }
        else{
     $text = $psise.CurrentFile.Editor.SelectedText
    }
    }
    elseif($Path){
        $text = (Get-Content $Path) -join “`r`n”
    }
    trap { break }
    # Do syntax parsing.
    $errors = $null
    $tokens = [system.management.automation.psparser]::Tokenize($Text, [ref] $errors)
# Initialize HTML builder.
    $codeBuilder = new-object system.text.stringbuilder
    $lineBuilder = new-object system.text.stringbuilder
    $null = $lineBuilder.Append(“{0:000}<BR />” -f $currentLine)
$SCRIPT:currentLine ++
# Iterate over the tokens and set the colors appropriately.
    $position = 0
    foreach ($token in $tokens){
        if ($position -lt $token.Start){
    $block = “Second”
            $block = $text.Substring($position, ($token.Start  $position))
            $tokenColor = ‘Unknown’
            Append-HtmlSpan $block $tokenColor
        }
$block = “First”
        $block = $text.Substring($token.Start, $token.Length)
        $tokenColor = $token.Type.ToString()
        Append-HtmlSpan $block $tokenColor
        $position = $token.Start + $token.Length
    }
    $code = $codeBuilder.ToString()
    $html = GetHtmlClipboardFormat $code “Print”
    $IEApplication = New-Object -ComObject InternetExplorer.Application
    $IEApplication.Navigate2(“about:blank”,14)
    $IEApplication.Visible = $false
    if($Host.Name -eq ‘Windows PowerShell ISE Host’){
        $IEApplication.Document.frames.document.title = $psise.CurrentFile.DisplayName
    }
    Else{
        $IEApplication.Document.frames.document.title = (Split-Path -Path $Path -Leaf)
    }
    $IEApplication.Document.body.innerHTML = $html
    while ($IEApplication.busy) {Start-Sleep -Seconds 1}
    $IEApplication.ExecWB(7,2)
    #region cleanup
    while ($IEApplication.busy) {Start-Sleep -Seconds 1}
    $IEApplication.Quit()
    #endregion
}
Copy-ToPrinter -Path $Path

I suggest saving the script to a local path (say c:\scripts) and adding a reference to your PowerShell ISE profile such as:

$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add(“Print Script”,{c:\scripts\Copy-ToPrinter.ps1},”Alt+Shift+P”) | Out-Null

You can either copy the script from above, or download it from TechNet

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: