header image

Testing module existence

Posted by: | April 9, 2014 | No Comment |

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 {
param (





switch ($psCmdlet.ParameterSetName) {
‘Installed’ {
                Get-Module -Name "*$name*" -ListAvailable
‘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


test-module -name cim -loaded

You can even do this:

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

under: Modules, PowerShell V3, PowerShell v4