Testing module existance

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”}

This entry was posted in Modules, PowerShell V3, PowerShell v4. Bookmark the permalink.

2 Responses to Testing module existance

  1. J says:

    This would only apply to ps3 but you could use a #requires for existence of modules

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s