Get list of functions from Script

If I have a .ps1 file with the following functions

function SomeFunction {}

function AnotherFunction {}

How can I get a list of all these functions and call them?

I would like to do something like this:

$functionsFromFile = Get-ListOfFunctions -Path 'C:\someScript.ps1'
foreach($function in $functionsFromFile)
{
   $function.Run() #SomeFunction and AnotherFunction execute
}
+2
source share
3 answers

You can use Get-ChildItemto extract all functions and save them in a variable. Then load the script into the workspace and load all the functions again and use the cmdlet Where-Objectto filter out all the new functions, excluding all previously extracted functions. Finally, iterate over all the new functions and call them:

$currentFunctions = Get-ChildItem function:
# dot source your script to load it to the current runspace
. "C:\someScript.ps1"
$scriptFunctions = Get-ChildItem function: | Where-Object { $currentFunctions -notcontains $_ }

$scriptFunctions | ForEach-Object {
      & $_.ScriptBlock
}
+3
source

script. , . , , - .

# Get text lines from file that contain 'function' 
$functionList = Select-String -Path $scriptName -Pattern "function"

# Iterate through all of the returned lines
foreach ($functionDef in $functionList)
{
    # Get index into string where function definition is and skip the space
    $funcIndex = ([string]$functionDef).LastIndexOf(" ") + 1

    # Get the function name from the end of the string
    $FunctionExport = ([string]$functionDef).Substring($funcIndex)

    Write-Output $FunctionExport
}

, . , - "", , , .

, "Get-ChildItem" .

"Select-String" "Function". "" "". , "-CaseSensitive".

, . "" , "", 9, , "".

$scriptPath = "c:\\Project"
$scriptFilter = "*.ps1"

( Get-ChildItem -Path $scriptPath -Filter $scriptFilter -Recurse | Select-String -Pattern "function" ) | %{ $_.Line.Substring(9) }
0

• 1.

, , Import-Module cmdlet

Functions.ps1 . .

function Write-TextColor
{
    Param(
        [parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [Object]
        $Info,

        [parameter(Position=1, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [System.ConsoleColor]
        $ForegroundColor =  [System.ConsoleColor]::White,

        [parameter(Position=2, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [Switch]
        $NoNewLine
        )

        Process{
            foreach ($value in $Info)
            {
                if($NoNewLine)
                {
                    Write-Host $value -ForegroundColor $ForegroundColor -NoNewline
                }
                else {
                    Write-Host $value -ForegroundColor $ForegroundColor
                }
            }            
        }
}
function Write-InfoBlue 
{
    Param(
        [parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [Object]
        $Information,

        [parameter(Position=1, ValueFromPipeline=$true)]
        [Switch]
        $NoNewLine
        )

    Process{
        Write-TextColor $Information Blue $NoNewLine
    }
}

Main.ps1

Import-Module -Name "$($PSCommandPath | Split-Path)/Functions.ps1" -Force
Write-InfoBlue "Printed from imported function."

Solution1


• 2.

Functions.ps1 . . , Solution1.

Main.ps1
3 .
1. Get-ScriptFunctionNames. String, .
2. Get-ScriptFunctionDefinitions. String, .
3. Get-AmalgamatedScriptFunctionDefinitions. , , Get-ScriptFunctionDefinitions. - Powershell.

3 .

function Get-ScriptFunctionNames {
    param (
        [parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Path
    )
    Process{
        [System.Collections.Generic.List[String]]$FX_NAMES = New-Object System.Collections.Generic.List[String]

        Select-String -Path "$Path" -Pattern "function" | 
        ForEach-Object {
            [Regex] $regexp = New-Object Regex("(function)( +)([\w-]+)")
            [Match] $match = $regexp.Match("$_")
            if($match.Success)
            {
                $FX_NAMES.Add("$($match.Groups[3])")
            }   
        }
        return $FX_NAMES.ToArray()
    }
}

function Get-ScriptFunctionDefinitions {

    param (
        [parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Path
    )
    Process{
        [System.Collections.Generic.List[String]]$FX_DEFS = New-Object System.Collections.Generic.List[String]

        Get-ScriptFunctionNames -Path $Path | 
        ForEach-Object {
            $fx = Get-Item "function:$_"
            if($fx -and ($null -ne $fx))
            {
                $FX_DEFS.Add("function $fx { $($fx.Definition) };")
            }
        }
        return $FX_DEFS.ToArray()
    }
}

function Get-AmalgamatedScriptFunctionDefinitions {

    param (
        [parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Path
    )
    Process{
        [System.String]$FX_DEFS = ""
        Get-ScriptFunctionDefinitions -Path $Path | 
        ForEach-Object {
            $FX_DEFS += "$_"
        }
        return $FX_DEFS
    }
}

Write-Host
[System.String[]]$FX_NAMES = Get-ScriptFunctionNames -Path "$($PSCommandPath | Split-Path)/Functions.ps1"
[System.String[]]$FX_DEFS = Get-ScriptFunctionDefinitions -Path "$($PSCommandPath | Split-Path)/Functions.ps1"
[System.String] $FX_ALL_DEFS = Get-AmalgamatedScriptFunctionDefinitions -Path "$($PSCommandPath | Split-Path)/Functions.ps1"

. ([System.Management.Automation.ScriptBlock]::Create($FX_ALL_DEFS)) #The functions in Functions.ps1 are created in the current script.
Write-InfoBlue "Printed from imported function."

Check: Dot Sourcing operator.
Dot Source
ScriptBlock class

Solution1

Main.ps1, 3 .

Write-Host "• TEST 1" -ForegroundColor Magenta
$FX_NAMES | 
ForEach-Object {
    Write-Host $_
}
Write-Host

Write-Host "• TEST 2" -ForegroundColor Magenta
foreach($value in $FX_DEFS)
{
    Write-Host $value
    Write-Host "███" -ForegroundColor DarkGray
}
Write-Host

Write-Host "• TEST 3" -ForegroundColor Magenta
Write-Host $FX_ALL_DEFS

Solution2-1 Solution2-2 Solution2-3



3. - , , .

powershell , Powershell Core .


PrintColorFunctions.ps1
, 1.

Main.ps1

$FX_ALL_DEFS = Get-AmalgamatedScriptFunctionDefinitions -Path "$($PSCommandPath | Split-Path)/Functions.ps1"
$R_HOST = "192.168.211.1" 
$R_USERNAME = "root" 
$R_PORT = "2222" 
$R_SESSION = New-PSSession -HostName $R_USERNAME@$($R_HOST):$R_PORT #//Connected by OpenSSL, private key added to OpenSSH Session Agent. If you need login by password, remove the private key from OpenSSH Session Agent and write as follows user:pass@host:port $($R_USERNAME):$R_PASS@$($R_HOST):$R_PORT
Invoke-Command -ArgumentList $FX_ALL_DEFS,"Joma" -Session $R_SESSION -ScriptBlock{ #// -ArgumentList function definitions and a name.
    Param($fxs, $name) #// Param received by remote context.
    . ([System.Management.Automation.ScriptBlock]::Create($fxs)) #//Creating function definitions in remote script context.

    Clear-Host
    Write-Host "Running commands in my remote Linux Server" -ForegroundColor Green #//Powershell Core cmdlet
    #//We can use Write-InfoBlue on this script context.
    Write-InfoBlue ($(Get-Content /etc/*-release | Select-String -Pattern "^PRETTY_NAME=.*" ).ToString().Split("=")[1]) #//Created function + cmdlets combo
    Write-InfoBlue $(uname -a) #//Created function + Native remote command
    Write-InfoBlue $(whoami) #//Cmdlet + Native remote command
    printf "Hello! $name" #//Native remote command
    Write-InfoBlue "Local function executed in remote context"
}
Remove-PSSession -Session $R_SESSION

Solution3

0

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


All Articles