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

前端 未结 5 1412
小鲜肉
小鲜肉 2020-12-13 01:15

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 n

相关标签:
5条回答
  • 2020-12-13 01:49

    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.

    0 讨论(0)
  • 2020-12-13 01:54

    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

    0 讨论(0)
  • 2020-12-13 01:54

    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
    }
    
    0 讨论(0)
  • 2020-12-13 02:05

    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
    }
    
    0 讨论(0)
  • 2020-12-13 02:11

    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
    
    0 讨论(0)
提交回复
热议问题