2012-03-15 73 views
7

我收到了Powershell中的以下编译问题。如何在添加前验证snapin?

Add-PSSnapin : Cannot add Windows PowerShell snap-in VMware.VimAutomation.Core because it is already added. Verify the name of the snap-in and try again.

错误清楚地提到我需要验证管理单元的名称。当我第一次执行它时,它被成功地添加了。

如何验证管理单元是否存在,如果不存在,那么添加?

+0

可能的重复[如何检查PowerShell管理单元是否在调用Add-PSSnapin之前已经加载](http://stackoverflow.com/questions/1477994/how-to-check-if-powershell-snap-in -is-已装载前方的呼唤 - 加 - pssnapin) – JohnC 2014-04-14 11:00:42

回答

11

如果没有加载您可以加载它:

if(-not (Get-PSSnapin VMware.VimAutomation.Core)) 
{ 
    Add-PSSnapin VMware.VimAutomation.Core 
} 

你也可以反正加载它,忽略错误:

Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue 
0

我得到了下面的错误,认为这是因为snapin已经加载,但似乎并非如此。

ERROR: The specified mount name 'vmstores' is already in use. 
ERROR: The specified mount name 'vis' is already in use. 

上面提供的解决方案肯定是比我开始写在下面更简单。

我假设一个促成因素是我期待看看snapin是否先注册。

$snaps1 = Get-PSSnapin -Registered 
$snaps2 = Get-PSSnapin *VMWare -ErrorAction SilentlyContinue 

$vmsnap = 0 

foreach ($snap1 in $snaps1) { 
    if ($snap1.name -eq "VMware.VimAutomation.Core") { 
     Write-Host "VM Snapin Registered..." 
     $vmsnap = 1 
     } 
    } 

if ($vmsnap -eq 0) { 
    Write-Host "VMWare Snapin NOT Registered. Ensure the CLI is installed and available on machine." 
} 

if ($vmsnap -eq 1) { 
    foreach ($snap2 in $snaps2) { 
     if($snap2.name -eq "VMware.VIMAutomation.Core") { 
      Write-Host "VMware Snapin Already Loaded..." 
      $vmsnap = 2 
      } 
     } 
    } 

if ($vmsnap -ne 2) { 
    Write-Host "Loading VMware Snapin..." 
Add-PSSnapin VMware.VimAutomation.Core 
} 

准予我对PS语法还是很新的。