'Check function exists in PowerShell module

I’ve the following PowerShell script which searches in a directory for PowerShell module). All found modules will be imported and stored in a list (using the -PassThru) option. The scrip iterates over the imported modules and invokes a function defined in the module:

# Discover and import all modules
$modules = New-Object System.Collections.Generic.List[System.Management.Automation.PSModuleInfo]
$moduleFiles = Get-ChildItem -Recurse -Path "$PSScriptRoot\MyModules\" -Filter "Module.psm1"
foreach( $x in $moduleFiles ) {
    $modules.Add( (Import-Module -Name $x.FullName -PassThru) )
}

# All configuration values
$config = @{
    KeyA = "ValueA"
    KeyB = "ValueB"
    KeyC = "ValueC"
}

# Invoke 'FunctionDefinedInModule' of each module
foreach( $module in $modules ) {
    # TODO: Check function 'FunctionDefinedInModule' exists in module '$module '
    & $module FunctionDefinedInModule $config
}

Now I would like to first check if a function is defined in a module before it gets invoked. How can such a check be implemented?

The reason for adding the check if to avoid the exception thrown when calling a function which doesn’t exists:

& : The term ‘FunctionDefinedInModule’ is not recognized as the name of a cmdlet, function, script file, or operable program


Solution 1:[1]

Get-Command can tell you this. You can even use module scope to be sure it comes from a specific module

get-command activedirectory\get-aduser -erroraction silentlycontinue

For example. Evaluate that in an if statement and you should be good to go.

Solution 2:[2]

Use Get-Command to check if a function currently exists

if (Get-Command 'FunctionDefinedInModule' -errorAction SilentlyContinue) {
    "FunctionDefinedInModule exists"
}

Solution 3:[3]

If many functions need to be checked

try{
    get-command -Name Get-MyFunction -ErrorAction Stop
    get-command -Name Get-MyFunction2 -ErrorAction Stop
}
catch{
    Write-host "Load Functions first prior to laod the current script"
}

Solution 4:[4]

I needed it so often that I wrote module for this.

Example

Solution 5:[5]

Maybe try adding this function to your module?

function DoesFunctionExists {
    param(
        [string]$Function
    )
    
    $FunList = gci function:$Function -ErrorAction 'SilentlyContinue'
    foreach ($FunItem in $FunList) {
        if ($FunItem.Name -eq $Function) {
            return $true
        }
    }
    return $false
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt
Solution 2 TobyU
Solution 3 Yann Greder
Solution 4 Pawel Wujczyk
Solution 5 Bimo