PwshSyntaxHighlight is a simple syntax highlighter for rendering PowerShell code blocks inside the terminal. This is a standalone version of the codeblock renderer I built for PowerShell AI.
Install-Module PwshSyntaxHighlight -Scope CurrentUser
Create some sample code to use in the examples below using a multi-line string variable like this.
$sampleCode = @'
function Test-ThisThingOut {
param (
[string] $Parameter
)
$message = "$Parameter is the parameter"
Write-Host "Hello PwshSyntaxHighlight! $message"
}
'@
Pass the code as the -Text
parameter to render a code block, use -SyntaxHighlight
to enable highlighting and -ShowLineNumbers
to show a gutter down the left containing the code line numbers.
Write-CodeBlock -Text $sampleCode -SyntaxHighlight -ShowLineNumbers
There are only two basic themes available at the moment, GitHub (default) and Matrix, if you're interested you could open a PR for more.
Write-CodeBlock -Text $sampleCode -SyntaxHighlight -ShowLineNumbers -Theme Matrix
# Provide a list of lines to highlight to draw attention to them with -HighlightLines
Write-CodeBlock $sampleCode -HighlightLines 2, 3, 4 -ShowLineNumbers
By passing a collection of Extents into Write-CodeBlock
you can have the extents highlighted in the rendered code. This is how errors are highlighted in the PowerShell AI Function Builder demo on YouTube.
Parsing PowerShell code with the built-in Abstract Syntax Tree is too much for me to document here but you can check out the awesome details available at powershell.one/powershell-internals/parsing-and-tokenization/abstract-syntax-tree if you're interested.
# Create a script block from the sample code
$scriptBlock = [ScriptBlock]::Create($sampleCode)
# Get a list of items from the abstract syntax tree that are double quoted strings
$astItems = $scriptBlock.Ast.FindAll({$args[0].StringConstantType -eq "DoubleQuoted"}, $true)
# Get the extents for all of those double quoted strings
$extents = $astItems | Select-Object -ExpandProperty Extent
$sampleCode | Write-CodeBlock -HighlightExtents $extents -ShowLineNumbers
@I_Am_Jakoby added the ability to take screenshots when this is run from a Windows based terminal π€
Use -ClearHost
and -ScreenShot
to clear the host, and save an image of the terminal window.
Write-CodeBlock $sampleCode -SyntaxHighlight -ShowLineNumbers -ClearHost -ScreenShot
The screenshot will include the window border and look a bit like this:
Another @I_Am_Jakoby special π
Use -Html
to save the code block as an html document.
Write-CodeBlock $sampleCode -SyntaxHighlight -ShowLineNumbers -Html
The command will save an HTML file you can open in your browser:
The colors don't match what you see in the terminal which will be corrected with #2