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

I have a group of PowerShell scripts that sometimes run together, sometimes one at a time. Each script requires the loading of a specific snap-in.

Currently, each script calls Add-PSSnapin XYZ at the beginning.

Now, if I run several scripts on the back of the following throw scripts:

You cannot add the Windows PowerShell XYZ snap-in because it is added. Check the snap-in name and try again.

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

+85
powershell
Sep 25 '09 at 15:28
source share
5 answers

You should do this with something like this, where you request Snapin, but don't tell PowerShell about the error if it cannot find it:

 if ( (Get-PSSnapin -Name MySnapin -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin MySnapin } 
+126
Sep 25 '09 at 16:09
source share
Scott has already given you the answer. You can also download it and ignore the error if it is already loaded:
 Add-PSSnapin -Name <snapin> -ErrorAction SilentlyContinue 
+20
Sep 25 '09 at 16:41
source share

Surprisingly, no one mentioned the native script path to indicate dependencies: the #REQUIRES -PSSnapin Microsoft.PowerShell... directive #REQUIRES -PSSnapin Microsoft.PowerShell... comment / preprocessor. Likewise, you could request a boost with -RunAsAdministrator , modules with -Modules Module1,Module2 and a specific version of Runspace.

Learn more by typing Get-Help about_requires

+4
Nov 20 '14 at 10:18
source share

I tried the @ScottSaad sample code, but that didn't work for me. I don’t know exactly why, but the check was unreliable, sometimes successful, and sometimes not. I found that the use of Where-Object filtering for the Name property has improved:

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

Code provided by this .

+3
Apr 30 '14 at 8:10
source share

Scott Saads works, but it seems a little faster to me. I did not rate it, but it seems to load a little faster, since it never creates an error.

 $snapinAdded = Get-PSSnapin | Select-String $snapinName if (!$snapinAdded) { Add-PSSnapin $snapinName } 
+1
Sep 17 '14 at 7:16
source share



All Articles