Home > PowerShell > Function: Set-ModuleStatus – PowerShell Function for Loading and Verifying Modules

Function: Set-ModuleStatus – PowerShell Function for Loading and Verifying Modules

PowerShell-logo-128x84Description

Often in my PowerShell scripts, I need to either load a specific module, or verify it’s loaded. Manually, of course, we can use Get-Module, Import-Module, etc. But in automation scripts, we need to programmatically make sure the module is loaded or load it if it’s not. I wrote this function and it’s worked well for me. introducing Get-ModuleStatus:

function Set-ModuleStatus { 
	[CmdletBinding(SupportsShouldProcess = $True)]
	param	(
		[parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, HelpMessage = "No module name specified!")] 
		[ValidateNotNullOrEmpty()]
		[string] $name
	)
	PROCESS{
		# Executes once for each pipeline object
		# the $_ variable represents the current input object		
		if (!(Get-Module -name "$name")) { 
			if (Get-Module -ListAvailable | Where-Object Name -eq "$name") { 
				Import-Module -Name "$name"
				# module was imported
				# return $true
			} else {
				# module was not available
				# return $false
			}
		} else {
			# Write-Output "$_ module already imported"
			# return $true
		} 
	} # end PROCESS
} # end function Set-ModuleStatus

Call it supplying the module name, such as

Set-ModuleStatus Lync

You can use logic such as

if (Set-ModuleStatus Lync){Write-Host "Lync module is loaded"}else{Write-Host "Lync module is NOT loaded" -ForegroundColor red}

Simple and effective. You can also pipe module names to it, such as:

“lync”,”activedirectory” | Set-ModuleStatus

Donations

I’ve never been one to really solicit donations for my work. My offerings are created because *I* need to solve a problem, and once I do, it makes sense to offer the results of my work to the public. I mean, let’s face it: I can’t be the only one with that particular issue, right? Quite often, to my surprise, I’m asked why I don’t have a “donate” button so people can donate a few bucks. I’ve never really put much thought into it. But those inquiries are coming more often now, so I’m yielding to them. If you’d like to donate, you can send a few bucks via PayPal at https://www.paypal.me/PatRichard. Money collected from that will go to the costs of my website (hosting and domain names), as well as to my home lab.

Download

v1.2 – 02-07-2014 – Set-ModuleStatus.v1.2.zip

v1.1 – 09-17-2012 - Set-ModuleStatus.v1.1.zip

v1.0 Get-ModuleStatus.ps1

Categories: PowerShell Tags: ,
  1. December 27th, 2011 at 10:20 | #1

    Very nice and a useful idea, but why are you piping results to Out-Null? I don’t get any results. It would also be a big help for people new to PowerShell if you would use cmdlet names instead of aliases like ‘?’ and ‘!’.

  2. Pat Richard
    December 27th, 2011 at 10:22 | #2

    The Out-Null is because I use the function in some deployment scripts that customers use, and I want to minimize output to the screen that’s rather unnecessary.

    Good point on the aliases.

  3. December 27th, 2011 at 10:30 | #3

    Except when you pipe to Null the function doesn’t really do anything so things like your If statement never work. I’ve written similar logic for this sort of thing and there are really two parts to this: Is the module current loaded in the session and is it available to load if it isn’t? So maybe what you want is a simple Test-Module, perhaps with two parameter sets, one -IsLoaded and another for -IsAvailable. Have these write True or False to the pipeline. Then you could do something like this:

    if (Test-Module MyModule -IsLoaded) {
    #carry on
    }
    elseif (test-module MyModule -IsAvailable) {
    Import-module Mymodule
    }
    else {
    Write-Warning “Can’t find or load MyModule”
    }

    • Pat Richard
      December 27th, 2011 at 10:37 | #4

      I respectfully disagree. Out-Null merely suppreses output to the screen – the function still works fine. If you do a Get-ModuleStatus BitsTransfer, then do a Get-Module, you’ll see that the module is in fact loaded (assuming it’s available on the machine you run it on).

  4. December 27th, 2011 at 10:47 | #5

    Of I see. I was thinking more along the lines about my earlier comments. You want to load the module if found. But something still doesn’t work. If I run a command like this:

    if (get-modulestatus BitsTransfer) {“ok”} else {“not found”}

    I get not found, even though BitsTransfer is already running. However that is only in the console. This always works in the ISE. Are you testing in both environments?

    • Pat Richard
      December 27th, 2011 at 11:07 | #6

      Okay – true enough – runnning it manually worked fine, but using it in an IF statement didn’t I’ve updated the code (just removed the Out-Null commands). Thanks, Jeff!

  5. Pat Richard
    December 27th, 2011 at 10:51 | #7

    Let me check. I haven’t tested that version in an IF statement in the console.

  6. December 27th, 2011 at 11:37 | #8

    You’ll need to fix your code since it is now in sections and you can’t copy it or view the source. Or add a text file download.

  7. Pat Richard
    December 27th, 2011 at 11:42 | #9

    Done. Thanks!

  8. December 27th, 2011 at 12:17 | #10

    Ok. That all seems to work now. I think my initial questions and comments were based on the function name. Usually when I see something with a Get verb, I don’t expect it to do anything other than give me some information. But in your case, you are actually importing the module as well. I like that you support ShouldProcess but you might re-think your function name to avoid confusion or misinterpretation. Although in looking at the verbs from Get-Verb, I’m really not sure what applies here.

  9. April 10th, 2012 at 03:03 | #11

    Agree with JHicks about the name of the function.
    “Get-…” should not have any side effects.

    Nice code though – helped me out.

  10. Pat Richard
    September 17th, 2012 at 20:48 | #12

    Updated to v1.1. Minor tweaks. Renamed to Set-ModuleStatus.

  11. August 28th, 2017 at 11:10 | #13

    Hi Pat,

    I’m curious, why don’t you simply Import-Module with -ErrorAction Stop? In a script, if you invoke Import-Module with -ErrorAction Stop it will:

    1. Raise a terminating error (because of -ErrorAction Stop) if the module is not on the system at all.
    2. Import the module if it is on the system but not loaded.
    3. Do nothing if the module is on the system and already loaded.

    Isn’t that the goal of the script you have shared here? Or is there something I’m missing?

    • August 28th, 2017 at 14:08 | #14

      Yeah, that’s like 6 years old. I often use a #Requires statement now, at least for scripts going into environments that support that. I probably should update that scheduled tweet.

  1. No trackbacks yet.