Parsing PowerShell Scripts

by May 11, 2015

If you'd like to create your own color-coded PowerShell scripts, for example formatting them in HTML, here is a sample that gets you started.

This sample takes the currently displayed script inside the ISE editor, and asks the PowerShell parser to return information about all tokens.

$content = $psise.CurrentFile.Editor.Text
$token = $null
$errors = $null

$token = [System.Management.Automation.PSParser]::Tokenize($content, [ref]$errors)

$token | Out-GridView

You could just as easily use Get-Content to read in the content of any script. The result is an array of token objects. They tell you what kind of language element it is, and where it actually starts and ends.

This information is what you need to reformat PowerShell source code. You could assign colors to token types, and create your own documentation for PowerShell source code.

Twitter This Tip! ReTweet this Tip!