Last active
June 9, 2019 10:47
-
-
Save JPRuskin/377d44d0c94ea955f3dabc29e37eeaee to your computer and use it in GitHub Desktop.
Function to list all functions within a script or scriptblock. Can then be piped to iex to effectively dot-source just the functions from a given file/block, or output to a file to concat a module of functions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-ScriptFunctions { | |
<# | |
.SYNOPSIS | |
Lists all functions within a script or scriptblock. | |
.DESCRIPTION | |
Uses AST to retrieve all functions from a valid script file or | |
scriptblock, then outputs them all. Useful for dot-sourcing | |
functions from a file that also contains running code. | |
.EXAMPLE | |
Get-ScriptFunctions -Export -ScriptPath .\testscript.ps1 | iex | |
.EXAMPLE | |
(Get-ScriptFunctions -ScriptPath .\testscript.ps1).Count | |
7 | |
#> | |
[CmdletBinding(DefaultParameterSetName='File')] | |
[OutputType([System.Management.Automation.Language.ScriptBlockAst[]])] | |
[OutputType([System.Management.Automation.Language.FunctionDefinitionAst[]])] | |
param( | |
# Filepath for script to analyse | |
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'File')] | |
[ValidateScript({Test-Path $_})] | |
[Alias('FullName')] | |
[IO.FileInfo[]]$ScriptPath, | |
# Scriptblock to analyse | |
[Parameter(Mandatory, ParameterSetName = 'Block')] | |
[ScriptBlock[]]$ScriptBlock, | |
# To export the functions alone, or with AST data | |
[Switch]$Export | |
) | |
process { | |
try { | |
switch ($PSCmdlet.ParameterSetName) { | |
'File' { | |
Write-Verbose "Analysing [$ScriptPath]" | |
$Script = [System.Management.Automation.Language.Parser]::ParseFile($ScriptPath, [ref]$null, [ref]$null) | |
} | |
'Block' { | |
Write-Verbose "Analysing [ScriptBlock]" | |
$Script = [System.Management.Automation.Language.Parser]::ParseInput($ScriptBlock, [ref]$null, [ref]$null) | |
} | |
} | |
} catch { | |
throw "Failed to parse $($PSCmdlet.ParameterSetName).`n$_" | |
} | |
try { | |
$functions = $Script.FindAll({$args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]}, $true) | |
Write-Verbose "Found $($functions.count) functions: $($functions.Name -join ', ')" | |
} catch { | |
throw "Failed to find functions in $($PSCmdlet.ParameterSetName).`n$_" | |
} | |
if ($Export) { | |
$functions.Extent | |
} else { | |
$functions | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment