Prof. Powershell

Module Testing

Make a statement for checking out modules.

If you write PowerShell 2.0 scripts and functions you most likely use the #Requires statement at the beginning of your code to indicate the minimum PowerShell version:

#Requires -version 2.0

There are also statements for checking pssnapins, but unfortunately, not for modules. Let me demonstrate a few ways you might handle this. First, we can use Get-Module to see if the module is even available:

$module="PSCX"
if (-not (Get-Module $module -ListAvailable)) {
  Write-Warning "Failed to find module $module"
  return
}
write-host "Continuing..."

If the PowerShell Community Extensions are not installed, I'll get a warning message and then the script will stop. The -Not operator essentially turns the Get-Module command on its ear and says, "If you don't find a module, then be true." Or perhaps you want to load the module if it isn't already running. Here's a slightly more involved solution:

$module="PSCX"
if (-not (Get-Module $module)) {
#module not running so see if it is available
  if (Get-Module $module -ListAvailable) {
    #if module is available load it
    Write-Host "loading $Module" -ForegroundColor Green
    Import-Module $module
  }
  else {
    Write-Warning "Failed to find or load $module"
    Return
  }
}

#module must already be running
write-host "Continuing..."

The first If statement checks if the module is already running. If so, then we continue. But if it isn't running, then we need to check if it is available. If so, then the module is imported. Otherwise the module isn't available so we display a warning message and bail.

There are certainly other ways you might handle this logic, perhaps even in a Try/Catch block or as a function. But I'll leave those exercises to you.

Don't forget that if you need help with any of your PowerShell projects, I hope you'll use the forums at ScriptingAnswers.com.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

SharePoint Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.