简体   繁体   English

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

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

I have a group of PowerShell scripts that sometimes get run together, sometimes one at a time. 我有一组PowerShell脚本有时可以一起运行,有时一次运行。 Each of the scripts requires that a certain snap-in be loaded. 每个脚本都要求加载某个管理单元。

Right now each script is calling Add-PSSnapin XYZ at the beginning. 现在每个脚本都在开头调用Add-PSSnapin XYZ

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. 无法添加Windows PowerShell管理单元XYZ,因为它已添加了alerady。 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? 在调用Add-PSSnapin之前,如何检查每个脚本以查看是否已加载管理单元?

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: 你应该可以用这样的东西来做,你在哪里查询Snapin但是如果找不到它就告诉PowerShell不要输出错误:

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

Surpisingly, nobody mentioned the native way for scripts to specify dependencies: the #REQUIRES -PSSnapin Microsoft.PowerShell... comment/preprocessor directive. 令人惊讶的是,没有人提到脚本指定依赖关系的本地方式: #REQUIRES -PSSnapin Microsoft.PowerShell... comment / preprocessor指令。 Just the same you could require elevation with -RunAsAdministrator , modules with -Modules Module1,Module2 , and a specific Runspace version. 您可以使用-RunAsAdministrator进行提升,使用-Modules Module1,Module2和特定的Runspace版本进行提升。

Read more by typing Get-Help about_requires 通过键入Get-Help about_requires了解更多信息

I tried @ScottSaad's code sample but it didn't work for me. 我试过@ScottSaad的代码示例,但它对我不起作用。 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: 我发现在Name属性上使用Where-Object过滤效果更好:

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. Scott Saads的作品,但对我来说似乎有点快。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM