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.

It retrieves the AST from one or more PS1 and/or PSM1 files, script blocks, or random arbitrary code.

It can also be used to only retrieve specific AST types such as the definition of one or more functions.

Get-MrPrivateCommand is another function in the module which is used to show private functions in a module.

Notice the private function named Get-MrFunctionRequirment.

Get-MrFunctionRequirment is a helper function that’s sandwiched between Get-MrAST and Get-MrRequiredModule.

I’ll use a little known trick in this example to run the Get-MrFunctionRequirment private function from outside of the module by invoking it within module scope. This is the same trick I use to determine the private functions in a module by comparing the exported commands to the ones that exist in module scope.

The Get-MrRequiredModule function is used to determine the required modules for one or more files or blocks of code.

When the Get-MrRequiredModule is used without its Detailed parameter, it simply returns what’s listed in the Requires statement of the individual PS1 and/or PSM1 files.

When its Detailed parameter is specified, it retrieves a list of all the commands used in the files and then returns the name of the function along with the module that the command is part of including built-in modules. This does require the module to exist on your system, but it’s great for figuring out what to add to the Requires statement. Of course, there’s no reason to add built-in modules to the requires statement.

As you can see, the previous example also shows how easy it would be to retrieve a list of all the commands used in a function or script with the AST for auditing purposes. Want to know if someone wrote a function that uses Write-Host? That would be no problem whatsoever for an entire module or hundreds of functions or scripts.

The MrModuleBuildTools PowerShell module along with all code found in this blog article can be found in my ModuleBuildTools repository on GitHub.

Thoughts, questions, comments? Please post them as a comment to this blog article.

µ

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: