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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With