How to check if PowerShell snap-in is already loaded before calling Add-PSSnapin

Tag: powershell Author: gghello Date: 2009-09-09

I have a group of PowerShell scripts that sometimes get run together, sometimes one at a time. Each of the scripts requires that a certain snap-in be loaded.

Right now each script is calling Add-PSSnapin XYZ at the beginning.

Now if I run multiple scripts back-to-back the subsequent scripts throw:

Cannot add Windows PowerShell snap-in XYZ because it is alerady added. Verify the name of the snap-in and try again.

How can I have each script check to see if the snap-in is already loaded before calling Add-PSSnapin?

Best Answer

You should be able to do it with something like this, where you query for the Snapin but tell PowerShell not to error out if it cannot find it:

if ( (Get-PSSnapin -Name MySnapin -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PsSnapin MySnapin
}

comments:

Ah-hah! This is exactly what I needed, thank you! I had tried something similar to this in my experimenting but I didn't know about the -ErrorAction SilentlyContinue.
The SilentlyContinue is because Get-PSSnapin doesn't quietly return null when if doesn't find the snap in by default. It errors out.
For the lazy: This article provides a full code example how to also check if a snap-in is registered before loading it.

Other Answer1

Scott already gave you the answer. You can also load it anyway and ignore the error if it's already loaded:

Add-PSSnapin -Name <snapin> -ErrorAction SilentlyContinue

comments:

That would also silently continue if the snap in did not load for other reasons like not being installed. Which could lead to difficult to diagnose problems for people using your script.
Right, in that case we can check first if the snap-in is registered.

Other Answer2

I tried @ScottSaad's code sample but it didn't work for me. I haven't found out exactly why but the check was unreliable, sometimes succeeding and sometimes not. I found that using a Where-Object filtering on the Name property worked better:

if ((Get-PSSnapin | ? { $_.Name -eq $SnapinName }) -eq $null) {
    Add-PSSnapin $SnapinName 
}

Code courtesy of this.