如何编写应检查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
答案 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
}
}
}