Function: Set-ModuleStatus – PowerShell Function for Loading and Verifying Modules
Description
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
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 ‘!’.
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.
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”
}
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).
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?
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!
Let me check. I haven’t tested that version in an IF statement in the console.
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.
Done. Thanks!
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.
Agree with JHicks about the name of the function.
“Get-…” should not have any side effects.
Nice code though – helped me out.
Updated to v1.1. Minor tweaks. Renamed to Set-ModuleStatus.
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?
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.