Climbing the Abstract Syntax Tree
If you’ve been using PowerShell for any length of time, you’ve noticed that features like tab completion fail if there is an error in your command. Or when using the PowerShell ISE or VS Code, you’ll get red squiggle marks indicating something is amiss with your code. These are but a few examples that indicate PowerShell is parsing your code as you write it. One of the things that makes this possible is the AST or Abstract Syntax Tree.
The AST was introduced in PowerShell v3 and has grown over time. Most PowerShell users don’t need to know anything about the AST or how it works. But if you are a subscriber to this newsletter, you are not an ordinary PowerShell user. While understanding the AST may not make you a better scripter, there may be AST features that you’d like to explore and experiment with.
The AST begins with the parser. This object class has two methods we’ll look at, beginning with ParseInput()
.
[System.Management.Automation.Language.Parser]::ParseInput.OverloadDefinitions
static System.Management.Automation.Language.ScriptBlockAst ParseInput(string input, [ref] System.Management.Automation.Language.Token[] tokens, [ref] System.Management.Automation.Language.ParseError[] errors)
static System.Management.Automation.Language.ScriptBlockAst ParseInput(string input, string fileName, [ref] System.Management.Automation.Language.Token[] tokens, [ref] System.Management.Automation.Language.ParseError[] errors)