Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check function exists in PowerShell module

Tags:

powershell

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
like image 831
musium Avatar asked Oct 04 '18 14:10

musium


People also ask

How do I know if a PowerShell module is loaded?

The if statement is used to see if the module is currently loaded. If it is not loaded, the Get-Module cmdlet is used to see if the module exists on the system. If it does exist, the module is loaded.

Are there functions in PowerShell?

A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.

How many functions are currently defined in your PowerShell environment?

There are two kinds of functions in PowerShell. We have a “basic” function and an advanced function. “Basic” functions are the simplest form of a function that can be created. They don't have any of the fancy built-in capabilities that advanced functions do.


1 Answers

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.

like image 121
Matt Avatar answered Oct 28 '22 12:10

Matt