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

Powershell

Powershell Problem Overview


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?

Powershell Solutions


Solution 1 - Powershell

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 - Powershell

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 - Powershell

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 - Powershell

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 - Powershell

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjoshuapoehlsView Question on Stackoverflow
Solution 1 - PowershellScott SaadView Answer on Stackoverflow
Solution 2 - PowershellShay LevyView Answer on Stackoverflow
Solution 3 - PowershellAlexeyView Answer on Stackoverflow
Solution 4 - PowershellAndy McCluggageView Answer on Stackoverflow
Solution 5 - PowershellKjetil YtrehusView Answer on Stackoverflow