Parsing PowerShell script with AST


I’m trying to parse through a Pester script and extract values from the -Tag parameter. Anyone know how to do this using [System.Management.Automation.PSParser]?. I’m was thinking I’d have to loop through the tokens returned from [System.Management.Automation.PSParser]::Tokenize() but that seems pretty kludgy and given that the values for -Tag could be given in many different formats, not very practical.

At the end of the day, I’m hoping to return a collection with the Describe block name, and the list of tags (if any) for that block.

Here are the sample Pester tests that I’m working with.

Anyone have any ideas on how to solve this? Is [System.Management.Automation.PSParser] the right way to go or is there a better way?



Using PS3.0+ Language namespace AST parser:

The code doesn’t interpret the tags as a list of strings, but simply uses the original text extent.
Use the debugger in PowerShell ISE / Visual Studio / VSCode to inspect the various data type cases.


Parsing PowerShell script with AST by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply