My Technical Notes

Friday, 6 March 2015

Getting all function names in a PowerShell module using C#

The following code gives all the module names within a powershell module. It uses the `System.Management.Automation` DLL found in


C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll

Here is the code:


string moduleFilePath = @"C:\Users\hasst001\Documents\WindowsPowerShell\Modules\MyModule\MyModule.psm1";
Token[] tokens;
ParseError[] errors;
var ast = System.Management.Automation.Language.Parser.ParseFile(moduleFilePath, out tokens, out errors);

var functionDefinitionAsts = 
    ast
    .FindAll(x => x is System.Management.Automation.Language.FunctionDefinitionAst, searchNestedScriptBlocks: false)
    .Cast<FunctionDefinitionAst>();

var functionNames = functionDefinitionAsts.Select(x => x.Name).ToList();
Console.WriteLine(string.Join("\r\n", functionNames));

No comments: