Is there an easier way to get a list of all the functions in a given Powershell script than matching the function signatures with a regex (in Powershell)?
I guess there are many ways. The one doesn't parse the file and is quite easy:
@"
function mya { write-host mya }
function myb { write-host myb }
Invoke-Expression "function hiddena { write-host by invoke-expression }"
"@ | set-content c:\test1.ps1
$functions = & {
$before = gci function:\
. c:\test1.ps1
$after = gci function:\
Compare-Object $before $after -SyncWindow $before.Length | Select -expand InputObject
}
$functions | ? { $_.Name -match 'a' }
> CommandType Name Definition
> ----------- ---- ----------
> Function hiddena write-host 'by invoke-expression'
> Function mya write-host 'mya'
I created a child scope where I imported the functions and then simply compared what was added. Whole the scriptblock returns added functions that you process further.
Note that if you use just tokenizer, you won't find the function hiddena
, because it is contained in a plain string. The same is if you would use e.g. Set-Content function:\testa -value { write-host 'by set-item' }
.
Here is a version that uses PowerShell's Tokenizer. Not sure if it is easier.
Using PowerShell’s PsParser::Tokenize, Discover Functions in PowerShell Scripts
If you know the full path of the script file that contains the functions and the functions are loaded in your session:
PS > dir function: | where {$_.scriptblock.file -eq 'd:\functions.ps1'}