2017-10-15 227 views
0

如何編寫應檢查Add-PSSnapin的代碼,如果該代碼不存在,則檢查Import-Module,如果該代碼也不存在,則退出該腳本。我編寫了下面的代碼,但在使用它時出現內存溢出問題。PowerShell中的導入模塊和Add-PSSnapin

cls 
Function GetModule { 

$ErrorActionPreference = 'Stop' 

if(-not(Get-Module -Name VMware.VimAutomation.Core)) 
{ 
Import-Module VMware.VimAutomation.Core 
} 

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

Else { 

Write-Host "VMware PowerCLI Modules are NOT INSTALLED on this machine !" 
Exit 
} 

} 

GetModule 

回答

0

您可以使用多個try/catch語句,與-ErrorAction Stop參數

Function GetModule { 

Try { 
Import-Module -Name VMware.VimAutomation.Core -ErrorAction Stop 
} 

catch { 

    Write-Host "Unable to load VMware PowerCLI Module, trying the PSSnapin..." 

    try { 
    Add-PSSnapin VMware.VimAutomation.Core -ErrorAction Stop 
    } 

     catch { 
     Write-Host "VMware PowerCLI Modules are NOT INSTALLED on this machine !" 
     return 
     } 
    } 

} 
+0

謝謝@Avshalom一起! 如果我想退出腳本,如果沒有找到/安裝在機器上的2個模塊?那麼在第二個catch中添加「EXIT」就可以解決這個問題? –

+0

是的,但它會自動退出,您可以在最後一個catch塊的末尾添加'return',更新我的答案。 – Avshalom