PowerShell中的Import-Module和Add-PSSnapin

时间:2017-10-15 07:13:50

标签: powershell-v3.0

如何编写应检查Add-PSSnapin的代码,如果它不存在则检查Import-Module,如果该代码也不存在则退出脚本。我编写了下面的代码,但在使用它时出现了内存溢出问题。

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

1 个答案:

答案 0 :(得分: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
        }
    }

}