Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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?

like image 888
joshuapoehls Avatar asked Sep 25 '09 15:09

joshuapoehls


People also ask

How do I add-PSSnapIn to PowerShell?

To use a snap-in in future Windows PowerShell sessions, add the Add-PsSnapin command to your Windows PowerShell profile. Or, export the snap-in names to a console file. If you add the Add-PSSnapin command to your profile, it is available in all future Windows PowerShell sessions.


2 Answers

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 } 
like image 96
Scott Saad Avatar answered Sep 22 '22 06:09

Scott Saad


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 
like image 40
Shay Levy Avatar answered Sep 25 '22 06:09

Shay Levy