Skip to content

Instantly share code, notes, and snippets.

@dfch
Last active March 12, 2018 22:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dfch/21a7dd47198b61ec2fd0 to your computer and use it in GitHub Desktop.
Save dfch/21a7dd47198b61ec2fd0 to your computer and use it in GitHub Desktop.
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