VMware Powercli Module

How to import VMware powercli snap-in automatically? Also I want the snap-in to be imported as a “Module” in PowerShell ISE

P.S.: I am newbie to Powershell. Requesting SOS with PowerCLI.

You would write a profile script. Those run each time you start the associated hosting application. You would put the Add-PSSnapin command (for example) in the profile. Run “help about_profile*” in the shell to read about profile scripts.

There’s no way to make a snap-in “imported as a Module.” I’m not sure what you mean by that. Modules and snap ins are different things.

But read some blogs and even experienced that merely running “add-PSSnapin vim.automation.core” adds the snap-in powershell. But doesn’t work as it works in Powercli Profile. Below is a script, these scripts run while launching the Powercli application. I would be very thankful if you could read these and help with one script, which if executed, would load the same snap-in or module in ISE.

This is in the Target Space: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -psc “C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1” -noe -c ". “C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"”

SCRIPT 1: vim.psc1
<?xml version=“1.0” encoding=“utf-8”?>
<PSConsoleFile ConsoleSchemaVersion=“1.0”>
<PSVersion>1.0</PSVersion>
<PSSnapIns>
<PSSnapIn Name=“VMware.VimAutomation.Core” />
<PSSnapIn Name=“VMware.VimAutomation.Vds” />
</PSSnapIns>
</PSConsoleFile>

SCRIPT 2: Initialize-PowerCLIEnvironment.ps1

#######################################################################################################################

This file will be removed when PowerCLI is uninstalled. To make your own scripts run when PowerCLI starts, create a

file named “Initialize-PowerCLIEnvironment_Custom.ps1” in the same directory as this file, and place your scripts in

it. The “Initialize-PowerCLIEnvironment_Custom.ps1” is not automatically deleted when PowerCLI is uninstalled.

#######################################################################################################################

$productName = “vSphere PowerCLI”
$productShortName = “PowerCLI”
$version = Get-PowerCLIVersion
$windowTitle = “VMware $productName {0}.{1}” -f $version.Major, $version.Minor
$host.ui.RawUI.WindowTitle = “$windowTitle”
$CustomInitScriptName = “Initialize-PowerCLIEnvironment_Custom.ps1”
$currentDir = Split-Path $MyInvocation.MyCommand.Path
$CustomInitScript = Join-Path $currentDir $CustomInitScriptName

#returns the version of Powershell

Note: When using, make sure to surround Get-PSVersion with parentheses to force value comparison

function Get-PSVersion {
if (test-path variable:psversiontable) {
$psversiontable.psversion
} else {
[version]“1.0.0.0”
}
}

Returns the path (with trailing backslash) to the directory where PowerCLI is installed.

function Get-InstallPath {
$regKeys = Get-ItemProperty “hklm:\software\VMware, Inc.\VMware vSphere PowerCLI” -ErrorAction SilentlyContinue

#64bit os fix
if($regKeys -eq $null){
$regKeys = Get-ItemProperty “hklm:\software\wow6432node\VMware, Inc.\VMware vSphere PowerCLI” -ErrorAction SilentlyContinue
}

return $regKeys.InstallPath
}

Loads additional snapins and their init scripts

function LoadSnapins(){
$snapinList = @( “VMware.VimAutomation.Core”, “VMware.VimAutomation.Vds”, “VMware.VimAutomation.License”, “VMware.DeployAutomation”, “VMware.ImageBuilder”, “VMware.VimAutomation.Cloud”)

$loaded = Get-PSSnapin -Name $snapinList -ErrorAction SilentlyContinue | % {$.Name}
$registered = Get-PSSnapin -Name $snapinList -Registered -ErrorAction SilentlyContinue | % {$
.Name}
$notLoaded = $registered | ? {$loaded -notcontains $_}

foreach ($snapin in $registered) {
if ($loaded -notcontains $snapin) {
Add-PSSnapin $snapin
}

  # Load the Intitialize-&lt;snapin_name_with_underscores&gt;.ps1 file
  # File lookup is based on install path instead of script folder because the PowerCLI
  # shortuts load this script through dot-sourcing and script path is not available.
  $filePath = "{0}Scripts\Initialize-{1}.ps1" -f (Get-InstallPath), $snapin.ToString().Replace(".", "_")
  if (Test-Path $filePath) {
     &amp; $filePath
  }

}
}
LoadSnapins

Update PowerCLI version after snap-in load

$version = Get-PowerCLIVersion
$windowTitle = “VMware $productName {0}.{1} Release 1” -f $version.Major, $version.Minor
$host.ui.RawUI.WindowTitle = “$windowTitle”

function global:Get-VICommand([string] $Name = "") {
get-command -pssnapin VMware.
-Name $Name
}

function global:Get-LicensingCommand([string] $Name = “*”) {
get-command -pssnapin VMware.VimAutomation.License -Name $Name
}

function global:Get-ImageBuilderCommand([string] $Name = “*”) {
get-command -pssnapin VMware.ImageBuilder -Name $Name
}

function global:Get-AutoDeployCommand([string] $Name = “*”) {
get-command -pssnapin VMware.DeployAutomation -Name $Name
}

Launch text

write-host " Welcome to the VMware $productName!"
write-host “”
write-host "Log in to a vCenter Server or ESX host: " -NoNewLine
write-host “Connect-VIServer” -foregroundcolor yellow
write-host "To find out what commands are available, type: " -NoNewLine
write-host “Get-VICommand” -foregroundcolor yellow
write-host "To show searchable help for all PowerCLI commands: " -NoNewLine
write-host “Get-PowerCLIHelp” -foregroundcolor yellow
write-host "Once you’ve connected, display all virtual machines: " -NoNewLine
write-host “Get-VM” -foregroundcolor yellow
write-host “If you need more help, visit the PowerCLI community: " -NoNewLine
write-host “Get-PowerCLICommunity” -foregroundcolor yellow
write-host “”
write-host " Copyright © 1998-2013 VMware, Inc. All rights reserved.”
write-host “”
write-host “”

Error message to update to version 2.0 of PowerShell

Note: Make sure to surround Get-PSVersion with parentheses to force value comparison

if((Get-PSVersion) -lt “2.0”){
$psVersion = Get-PSVersion
Write-Error “$productShortName requires Powershell 2.0! The version of Powershell installed on this computer is $psVersion.” -Category NotInstalled
}

Modify the prompt function to change the console prompt.

Save the previous function, to allow restoring it back.

$originalPromptFunction = $function:prompt
function global:prompt{

# change prompt text
Write-Host "$productShortName " -NoNewLine -foregroundcolor Green
Write-Host ((Get-location).Path + "&gt;") -NoNewLine
return " "

}

Tab Expansion for parameters of enum types.

This functionality requires powershell 2.0

Note: Make sure to surround Get-PSVersion with parentheses to force value comparison

if((Get-PSVersion) -eq “2.0”){

#modify the tab expansion function to support enum parameter expansion
$global:originalTabExpansionFunction = $function:TabExpansion

function global:TabExpansion {
   param($line, $lastWord)
   
   $originalResult = &amp; $global:originalTabExpansionFunction $line $lastWord
   
   if ($originalResult) {
      return $originalResult
   }
   #ignore parsing errors. if there are errors in the syntax, try anyway
   $tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null)
   
   if ($tokens)
   {
       $lastToken = $tokens[$tokens.count - 1]
       
       $startsWith = ""
       
       # locate the last parameter token, which value is to be expanded
       switch($lastToken.Type){
           'CommandParameter' {
                #... -Parameter&lt;space&gt;
                
                $paramToken = $lastToken
           }
           'CommandArgument' {
                #if the last token is argument, that can be a partially spelled value
                if($lastWord){
                    #... -Parameter Argument  &lt;&lt;&lt; partially spelled argument, $lastWord == Argument
                    #... -Parameter Argument Argument
                    
                    $startsWith = $lastWord
                    
                    $prevToken = $tokens[$tokens.count - 2]
                    #if the argument is not preceeded by a paramter, then it is a value for a positional parameter.
                    if ($prevToken.Type -eq 'CommandParameter') {
                        $paramToken = $prevToken
                    }
                }
                #else handles "... -Parameter Argument&lt;space&gt;" and "... -Parameter Argument Argument&lt;space&gt;" &gt;&gt;&gt; which means the argument is entirely spelled
           }
       }
       
       # if a parameter is found for the argument that is tab-expanded
       if ($paramToken) {        
           #locates the 'command' token, that this parameter belongs to
           [int]$groupLevel = 0
           for($i=$tokens.Count-1; $i -ge 0; $i--) {
               $currentToken = $tokens[$i]
               if ( ($currentToken.Type -eq 'Command') -and ($groupLevel -eq 0) ) {
                  $cmdletToken = $currentToken
                  break;
               }
               
               if ($currentToken.Type -eq 'GroupEnd') {
                  $groupLevel += 1
               }
               if ($currentToken.Type -eq 'GroupStart') {
                  $groupLevel -= 1
               }
           }
           
           if ($cmdletToken) {
               # getting command object
               $cmdlet = Get-Command $cmdletToken.Content
               # gettint parameter information
               $parameter = $cmdlet.Parameters[$paramToken.Content.Replace('-','')]
               
               # getting the data type of the parameter
               $parameterType = $parameter.ParameterType
               
               if ($parameterType.IsEnum) {
                  # if the type is Enum then the values are the enum values
                  $values = [System.Enum]::GetValues($parameterType)
               } elseif($parameterType.IsArray) {
                  $elementType = $parameterType.GetElementType()
                  
                  if($elementType.IsEnum) { 
                    # if the type is an array of Enum then values are the enum values
                    $values = [System.Enum]::GetValues($elementType) 
                  }
               }
               
               if($values) {
                  if ($startsWith) {
                      return ($values | where { $_ -like "${startsWith}*" })
                  } else {
                      return $values
                  }
               }
           }
       }
   } 
}

}

Opens documentation file

function global:Get-PowerCLIHelp{
$ChmFilePath = Join-Path (Get-InstallPath) “VICore Documentation$productName Cmdlets Reference.chm”
$docProcess = [System.Diagnostics.Process]::Start($ChmFilePath)
}

Opens toolkit community url with default browser

function global:Get-PowerCLICommunity{
$link = “http://communities.vmware.com/community/vmtn/vsphere/automationtools/windows_toolkit
$browserProcess = [System.Diagnostics.Process]::Start($link)
}

Find and execute custom initialization file

$existsCustomInitScript = Test-Path $CustomInitScript
if($existsCustomInitScript) {
& $CustomInitScript
}

Unfortunately, no, I can’t read through a script of that size and tell you what’s wrong with it.

It’s likely that PowerCli is typically loaded through a script, which may also define functions, variables, and other items. You’d probably get a better answer to your question in the PowerCli forums on Vmware’s community site. We regularly refer people there, in fact.