[NoBrainer] Enumerate all functions in a PowerShell script file via AST

Recently I needed to check if a function was defined inside a script file. Reflection was my first thought, and PowerShell being a first class .NET citizen should be able to perform this. But as PowerShell is defined as an Abstract Syntax Tree (AST) it is even easier to achieve this.

Inside the AST every block (BEGIN, PROCESS, END) is an object you can investigate upon. And inside such a block you can see all statements and their extents. As every function has to start with the function keyword, you only have to see if the statement’s extent start with that keyword and check if that name corresponds to the statement’s name: ![String]::IsNullOrWhiteSpace($Statement.Name) -And $Extent -imatch ('function\W+(?{0})' -f $Statement.Name). That’s all to it.

In this Gist you see a full example that enumerates all functions inside the file:

The output should look similar to this:

PS > .Get-Functions.ps1
functionInBeginBlock
getFunctions
functionInProcessBlock
functionInEndBlock
theAnswer

Note: you can certainly use this to list functions in other script files as well. You can use the ParseFile instead and continue from there.
You find more information on PowerShell and AST on MSDN and elsewhere. Two links to get started:

Trackbacks

  1. […] Source: [NoBrainer] Enumerate all functions in a PowerShell script file via AST – d-fens GmbH […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: