Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enumerate all functions in a PowerShell script file via AST
#Requires -Version 3
# http://d-fens.ch/2015/04/26/nobrainer-enumerate-all-functions-in-a-powershell-script-file-via-ast
[CmdletBinding(
SupportsShouldProcess = $true
,
ConfirmImpact = 'Low'
,
DefaultParameterSetName = 'list'
)]
Param
(
[Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'list')]
[Switch]
$ListAvailable = $true
)
BEGIN
{
function functionInBeginBlock()
{
return "functionInBeginBlock";
}
function getFunctions($_MyInvocation)
{
$OutputParameter = @();
foreach($BlockName in @("BeginBlock", "ProcessBlock", "EndBlock"))
{
$CurrentBlock = $_MyInvocation.MyCommand.ScriptBlock.Ast.$BlockName;
foreach($Statement in $CurrentBlock.Statements)
{
$Extent = $Statement.Extent.ToString();
if([String]::IsNullOrWhiteSpace($Statement.Name) -Or $Extent -inotmatch ('function\W+(?<name>{0})' -f $Statement.Name))
{
continue;
}
$OutputParameter += $Statement.Name;
}
}
return $OutputParameter;
}
}
PROCESS
{
function functionInProcessBlock()
{
return "functionInProcessBlock";
}
}
END
{
function functionInEndBlock()
{
return "functionInEndBlock";
}
function theAnswer()
{
return 42;
}
return getFunctions($MyInvocation);
}
##
#
#
# Copyright 2015 Ronald Rink, d-fens GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment