views:

55

answers:

3

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)?

+2  A: 

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' }.

stej
Very clever! Nice use of compare and the function provider.
Mike Shepard
Thx, added some info why this imho could be better than parsing ;)
stej
1+ Thanks, in the end I used a simpler version that returned the functions themselves so I could call them directly.
Willbill
+2  A: 

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

Doug Finke
+1  A: 

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'}

Shay Levy
1+ good suggestion, I accepted stej's because his use of a child-scope allows you to look into any file without having to pull the functions into the current scope potentially risking overwriting the functions which are already loaded.
Willbill