如何检查 PowerShell 管理单元是否已经在调用 Add-PSSnap 之前加载

我有一组 PowerShell 脚本,它们有时一起运行,有时一次运行一个。每个脚本都需要加载某个管理单元。

现在每个脚本都在开始调用 Add-PSSnapin XYZ

现在,如果我连续运行多个脚本,随后的脚本会抛出:

无法添加 Windows PowerShell 管理单元 XYZ,因为它已被添加。请验证管理单元的名称,然后再试一次。

在调用 Add-PSSnap 之前,如何让每个脚本检查管理单元是否已经加载?

70878 次浏览

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

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.

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
}

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