Home > Back-end >  How to get all functions defined in a .ps1 file?
How to get all functions defined in a .ps1 file?

Time:10-02

I have some functions defined in a .ps1 file, which I can import them by a dot operator (. .\script.ps1). After that, I can use these functions in my powershell terminal. If it's a module, I could use the gcm -module ... command to get all commands from the module. But here it's a file, not a module. Is there a way for me to list all functions defined in the file? Like gcm -file "script.ps1".

CodePudding user response:

You can achieve this indirectly, by querying the .File property of the .ScriptBlock property of function objects (System.Management.Automation.FunctionInfo):

  • To match by script file name only:

    Get-Command -Type Function | 
      Where-Object { $_.ScriptBlock.File -like '*[\/]script.ps1' } | 
      ForEach-Object Name
    
  • To avoid ambiguity, you should match against the full script path, not just the file name, e.g.:

    Get-Command -Type Function | 
      Where-Object { $_.ScriptBlock.File -eq 'C:\path\to\script.ps1' } | 
      ForEach-Object Name
    
    • Note that .File always reports the path as a file-system-native one, even if you dot-sourced the script via a PowerShell-only drive. When in doubt, use Convert-Path on a path in order to convert it to a file-system-native one.

Santiago Squarzon points to an interesting variation of your task: Get the list of all functions directly from a script file (.ps1), irrespective of whether the script has been dot-sourced or not (i.e., irrespective of whether the functions have (already) been defined in the session):

# Returns the names of all functions defined in specified script
(Get-Command 'C:\path\to\script.ps1').ScriptBlock.Ast.FindAll(
  { $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] },
  $false # parameter `searchNestedScriptBlocks`
).Name

See also:

  • Related