Categories

Testing module existence

I had a comment left on an old post stating that Get-ADuser errored stating it wasn’t a cmdlet.  This is because the module wasn’t loaded or on PowerShell 3 and above available to be auto-imported.  That got me thinking about testing for a modules existence.

function test-module {
[CmdletBinding()]
param (

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$name,

[Parameter(ParameterSetName='Installed')]
[switch]$installed,

[Parameter(ParameterSetName='Loaded')]
[switch]$loaded

)

switch ($psCmdlet.ParameterSetName) {
'Installed' {
                Get-Module -Name "*$name*" -ListAvailable
                break
             }
'Loaded'    {
                Get-Module -Name "*$name*"

             }
default     {
                Throw "Error!!! Should not be here"
             }
}

}

Define a parameter for the module name and 2 switch parameters – loaded tests if the module is loaded into PowerShell and installed tests if the module can be found on the module path.

I’ve used parameter sets to make the switches mutually exclusive. 

A switch statement based on the parameter set name calls the Get-Module in an appropriate manner. Notice that the module name you supply is wrapped in wildcards so you don’t have to type the full module name.

You can use the function like this:

test-module -name cim –installed

or

test-module -name cim -loaded

You can even do this:

if (-not (test-module -name cim -loaded)){throw "module not found"}

Leave a Reply