tags:

views:

1402

answers:

2

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?

+8  A: 

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
}
Scott Saad
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.
Joshua Poehls
+3  A: 

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
Shay Levy