首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell中的导入模块和添加PSSnapin

PowerShell中的导入模块和添加PSSnapin
EN

Stack Overflow用户
提问于 2017-10-15 15:13:50
回答 1查看 603关注 0票数 0

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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2017-10-15 19:55:44

您可以使用多个try/catch以及-ErrorAction Stop参数

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46752624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档