PowerShell for Windows Admins

Apr 9 2014   1:33PM GMT

Testing module existence

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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


 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: