Private/GetFunctionByFile.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Function GetFunctionByFile {
    [CmdletBinding()]
    param (
        [string[]]$FilePath
    )

    $psMajorVersion = $PSVersionTable.PSVersion.Major
    $functionsInFile = @()
    ForEach ($thisFilePath in $FilePath) {
        Write-Verbose "Working on file : $thisFilePath"

        if (-not (Test-Path $thisFilePath)) {
            Write-Warning "Cannot find file : $thisFilePath"
            continue
        }

        try {
            Switch ($psMajorVersion) {
                '2' {
                    $scriptBlockInFile = [ScriptBlock]::Create($(Get-Content $thisFilePath) -join [Environment]::NewLine)
                    $functionsInFile += @(FindFunction -ScriptBlock $scriptBlockInFile)
                }
                Default {
                    $AST = [System.Management.Automation.Language.Parser]::ParseFile($thisFilePath, [ref]$null, [ref]$null)
                    $functionsInFile += $AST.FindAll( {$args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]} , $true)
                }
            }
            Write-Verbose "Functions found in file : $($functionsInFile.Name -join '; ')"
        }
        catch {
            Write-Warning "$thisFilePath : $($_.Exception.Message)"
        }
    }
    $functionsInFile
}