Hello everyone,
As you may know from past experience or from reading the Forums Tips and Guidelines sticky, there are a couple of quirks with the forum software we’re using here related to CODE tags and backtick characters. The forum software treats backticks as special characters, which is quite annoying if your code contains any of them, and you’ll find that using PRE tags will give you much better results than CODE, particularly if someone tries to copy and paste your code into another window.
I’ve added a function to my PowerShell ISE profile which avoids these headaches by taking the code in the ISE’s active window, escaping it in such a way that the forum will display it properly, wraps it in PRE tags (and also adds a blank comment line to the beginning and end of the code, to make copy / paste easier), and pipes the results to the clipboard. All I have to do is press F7 and then paste into the forum window. The function was even used to post itself here, which is about as good of a success indicator as I can think of.
# function ConvertTo-PowerShellOrgPost { [CmdletBinding(DefaultParameterSetName = 'IseTab')] param ( [Parameter(ParameterSetName = 'FromPipeline', ValueFromPipeline = $true)] [string[]] $Code ) begin { if ($PSCmdlet.ParameterSetName -eq 'IseTab') { if ($null -eq $psISE) { throw 'If you do not specify a value for the Code parameter, this function may only be run from within the PowerShell ISE.' } if ($null -eq $psISE.CurrentFile) { throw 'There is no file editor currently open in the ISE.' } } $htmlEncode = { param ( [System.Text.RegularExpressions.Match] $Match ) $stringBuilder = New-Object System.Text.StringBuilder $null = $stringBuilder.Append('&') foreach ($char in $Match.Groups[1].Value.ToCharArray()) { $ascii = [int]$char $null = $stringBuilder.Append("&#$ascii;") } $null = $stringBuilder.Append(';') return $stringBuilder.ToString() } Write-Output '<pre>' Write-Output '#' } process { if ($PSCmdlet.ParameterSetName -eq 'IseTab') { $text = @($psISE.CurrentFile.Editor.Text) } else { $text = @($Code) } foreach ($line in $text) { $line = [regex]::Replace($line, '&(\S+?);', $htmlEncode) $line = $line -replace '`', '`' $line = $line -replace '<pre>', '<pre>' $line = $line -replace '</pre>', '</pre>' Write-Output $line } } end { Write-Output '#' Write-Output '</pre>' } } $null = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Format PowerShell.org Post To Clipboard", { ConvertTo-PowerShellOrgPost | clip.exe }, 'F7') #