Extracting functions from a script file

Is there an easier way to get a list of all the functions in a given Powershell script than matching function signatures with a regular expression (in Powershell)?

+3
source share
3 answers

I think there are many ways. One does not parse the file and is pretty 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 area where I imported the functions and then simply compared what was added. The entire script block returns additional functions that you process further.

, , hiddena, . , , , Set-Content function:\testa -value { write-host 'by set-item' }.

+4
+3

If you know the full path to the script file that contains the functions, and the functions are loaded into your session:

PS> dir function: | where {$ _. scriptblock.file -eq 'd: \ functions.ps1'}

+3
source

Source: https://habr.com/ru/post/1760495/


All Articles