You have developed a PowerShell script and you would like to share the script code with the community by posting it in a Wiki article?
If your answer is “yes”, the PowerShell script code below can help you.

When you run the script, you need to specify the full name of the PowerShell script you want to share as parameter.
The script reads your PowerShell script code and puts a “nice looking” representation of it into your clipboard.

When the script has finished, all you need to do is to click at the location in your Wiki article where you want the script code to show up, and then paste it (“Ctrl + V”).

Script Code

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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
[CmdletBinding()] 
param($path) 

function Get-ScriptName 
{ 
    $myInvocation.ScriptName 
} 

if($path -and ([Threading.Thread]::CurrentThread.ApartmentState -ne "STA")) 
{ 
    PowerShell -NoProfile -STA -File (Get-ScriptName) $path 
    return 
} 

$tokenColours = @{ 
    'Attribute'          = 'LightBlue' 
    'Command'            = 'Blue' 
    'CommandArgument'    = 'BlueViolet' 
    'CommandParameter'   = 'Navy' 
    'Comment'            = 'DarkGreen' 
    'GroupEnd'           = 'Black' 
    'GroupStart'         = 'Black' 
    'Keyword'            = 'DarkBlue' 
    'LineContinuation'   = 'Black' 
    'LoopLabel'          = 'DarkBlue' 
    'Member'             = 'Black' 
    'NewLine'            = 'Black' 
    'Number'             = 'Navy' 
    'Operator'           = 'DarkGray' 
    'Position'           = 'Black' 
    'StatementSeparator' = 'Black' 
    'String'             = 'DarkRed' 
    'Type'               = 'Teal' 
    'Unknown'            = 'Black' 
    'Variable'           = 'OrangeRed' 
} 

if($psise) 
{ 
    $tokenColours = $psise.Options.TokenColors 
} 

Add-Type -Assembly System.Web 
Add-Type -Assembly PresentationCore 

# Create RTF block from text using named console colors.
function Append-RtfBlock ($block, $tokenColor) 
{ 
    $colorIndex = $rtfColorMap.$tokenColor 
    $block = $block.Replace('\','\\').Replace("`r`n","\cf1\par`r`n") 
    $block = $block.Replace("`t",'\tab').Replace('{','\{').Replace('}','\}') 
    $null = $rtfBuilder.Append("\cf$colorIndex $block") 
} 

# Generate an HTML span and append it to HTML string builder
$currentLine = 1 
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') 
        { 
            $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) 
{ 
    $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 style='font-family:Consolas,Lucida Console; font-size:10pt;
    height:500px; border:1px solid black; overflow:auto; padding:5px'>
<TABLE BORDER='0' cellpadding='5' cellspacing='0'>
<TBODY>
<TR>
    <TD VALIGN='Top'>
<DIV style='font-family:Consolas,Lucida Console; font-size:10pt;
    padding:5px; background:LightGray'>
__LINES__
</DIV>
    </TD>
    <TD VALIGN='Top' NOWRAP='NOWRAP'>
<DIV style='font-family:Consolas,Lucida Console; font-size:10pt;
    padding:5px; background:WhiteSmoke'>
__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 
    $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) 
    $header = $header.Replace("__HTML__", $html) 
    
    Write-Verbose $header 
    $header 
} 

function Main 
{ 
    $text = $null 
    
    if($path) 
    { 
        $text = (Get-Content $path) -join "`r`n" 
    } 
    else 
    { 
        if (-not $psise.CurrentOpenedFile) 
        { 
            Write-Error 'No script is available for copying.' 
            return 
        } 
        
        $text = $psise.CurrentOpenedFile.Editor.Text 
    } 

    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++ 
   

    # Initialize RTF builder.
    $rtfBuilder = new-object system.text.stringbuilder 
    
    # Append RTF header
    $header = "{\rtf1\fbidis\ansi\ansicpg1252\deff0\deflang1033{\fonttbl" + 
        "{\f0\fnil\fcharset0 $fontName;}}" 
    $null = $rtfBuilder.Append($header) 
    $null = $rtfBuilder.Append("`r`n") 

    # Append RTF color table which will contain all Powershell console colors.
    $null = $rtfBuilder.Append("{\colortbl ;") 
    
    # Generate RTF color definitions for each token type.
    $rtfColorIndex = 1 
    $rtfColors = @{} 
    $rtfColorMap = @{} 
    
    [Enum]::GetNames([System.Management.Automation.PSTokenType]) | % { 
        $tokenColor = $tokenColours[$_]; 
        $rtfColor = "\red$($tokenColor.R)\green$($tokenColor.G)\blue" + 
            "$($tokenColor.B);" 
        if ($rtfColors.Keys -notcontains $rtfColor) 
        { 
            $rtfColors.$rtfColor = $rtfColorIndex 
            $null = $rtfBuilder.Append($rtfColor) 
            $rtfColorMap.$_ = $rtfColorIndex 
            $rtfColorIndex ++ 
        } 
        else 
        { 
            $rtfColorMap.$_ = $rtfColors.$rtfColor 
        } 
    } 
    
    $null = $rtfBuilder.Append('}') 
    $null = $rtfBuilder.Append("`r`n") 
    
    # Append RTF document settings.
    $null = $rtfBuilder.Append('\viewkind4\uc1\pard\f0\fs20 ') 
    
    # Iterate over the tokens and set the colors appropriately.
    $position = 0 
    foreach ($token in $tokens) 
    { 
        if ($position -lt $token.Start) 
        { 
            $block = $text.Substring($position, ($token.Start - $position)) 
            $tokenColor = 'Unknown' 
            Append-RtfBlock $block $tokenColor 
            Append-HtmlSpan $block $tokenColor 
        } 
        
        $block = $text.Substring($token.Start, $token.Length) 
        $tokenColor = $token.Type.ToString() 
        Append-RtfBlock $block $tokenColor 
        Append-HtmlSpan $block $tokenColor 
        
        $position = $token.Start + $token.Length 
    } 

    # Append RTF ending brace.
    $null = $rtfBuilder.Append('}') 
    
    # Copy console screen buffer contents to clipboard in three formats -
    # text, HTML and RTF.
    $dataObject = New-Object Windows.DataObject 
    $dataObject.SetText([string]$text, [Windows.TextDataFormat]"UnicodeText") 
    $rtf = $rtfBuilder.ToString() 
    $dataObject.SetText([string]$rtf, [Windows.TextDataFormat]"Rtf") 
    $code = $codeBuilder.ToString() 
    $html = GetHtmlClipboardFormat($code) 
    
    $dataObject.SetText([string]$html, [Windows.TextDataFormat]"Html") 

    [Windows.Clipboard]::SetDataObject($dataObject, $true) 
    Write-Host "Done..."
} 

. Main