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

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?


Solution 1:

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
}

Solution 2:

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

Solution 3:

Surpisingly, nobody mentioned the native way for scripts to specify dependencies: the #REQUIRES -PSSnapin Microsoft.PowerShell... comment/preprocessor directive. Just the same you could require elevation with -RunAsAdministrator, modules with -Modules Module1,Module2, and a specific Runspace version.

Read more by typing Get-Help about_requires

Solution 4:

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.

Solution 5:

Scott Saads works but this seems somewhat quicker to me. I have not measured it but it seems to load just a little bit faster as it never produces an errormessage.

$snapinAdded = Get-PSSnapin | Select-String $snapinName
if (!$snapinAdded)
{
    Add-PSSnapin $snapinName
}