Use the Abstract Syntax Tree (AST) to list parameters and variables in PowerShell functions

One thing I’ve missed during the past couple of years with virtual-only conferences is the hallway track. While at the PowerShell + DevOps Global Summit 2022, there was a discussion about using PascalCase for parameter names and camelCase for user-defined variables in your PowerShell functions. Specifying different casings depending on the usage seems like a great idea. Determining where you defined your variables would be self-explanatory. The only problem is you need something to verify that you’ve specified them in the correct case....

May 12, 2022 · 3 min · 634 words · Mike F. Robbins

Use the Abstract Syntax Tree (AST) to inspect PowerShell command syntax in scripts

I recently needed to determine the PowerShell commands and parameters used in multiple scripts. What better way to accomplish this task than to use the Abstract Syntax Tree (AST)? The Get-MrSyntax function begins by requiring at least PowerShell version 3.0. This is the oldest version that exposes the AST. The Path parameter uses ValidateScript for parameter validation to only accept files with a PS1 or PSM1 extension. The path(s) to the script files can be specified via pipeline or parameter input....

April 8, 2022 · 2 min · 340 words · Mike F. Robbins

Using the AST to Find Module Dependencies in PowerShell Functions and Scripts

Earlier this week, Chris Gardner presented a session on Managing dependencies in PowerShell for the Mississippi PowerShell User Group. I mentioned that I had written a function to retrieve PowerShell module dependencies that’s part of my ModuleBuildTools module. Get-MrAST is one of the primary functions that numerous other functions in the module are built on. #Requires -Version 3.0 function Get-MrAst { <# .SYNOPSIS Explores the Abstract Syntax Tree (AST). .DESCRIPTION Get-MrAST is an advanced function that provides a mechanism for exploring the Abstract Syntax Tree (AST)....

May 17, 2019 · 6 min · 1262 words · Mike F. Robbins

PowerShell Tokenizer more Accurate than AST in Certain Scenarios

As many of you know, I’ve been working on some module building tools. One of the things I needed was to retrieve a list of PowerShell modules that each function required (a list of dependencies). This seemed simple enough through PowerShell’s AST (Abstract Syntax Tree) as shown in the following example. $File = 'U:\GitHub\PowerShell\MrToolkit\Public\Find-MrModuleUpdate.ps1' $AST = [System.Management.Automation.Language.Parser]::ParseFile($File, [ref]$null, [ref]$null) $AST.ScriptRequirements.RequiredModules.Name The modules that are retrieved by the AST are simply the ones specified in a functions Requires statement....

February 21, 2019 · 3 min · 454 words · Mike F. Robbins