PowerCLI

VMware PowerCLI 4.1 Cmdlets Summarized by Noun

Here is the list of VMware PowerCLI cmdlets ordered by noun. I find this easier to use when I am trying to write scripts. You can locate what items you want to work with and then see the action you can take. This post contains the code used to generate the list.

Noun Verbs
Annotation Get,Set
CDDrive Get,New,Remove,Set
Cluster Get,Move,New,Remove,Set
CustomAttribute Get,New,Remove,Set
CustomField New,Remove,Set
Datacenter Get,Move,New,Remove,Set
Datastore Get,New,Remove,Set
DatastoreItem Copy
DrsRecommendation Apply,Get
DrsRule Get,New,Remove,Set
ErrorReport Get
FloppyDrive Get,New,Remove,Set
Folder Get,Move,New,Remove,Set
HardDisk Copy,Get,New,Remove,Set
Inventory Get,Move,Remove
IScsiHbaTarget Get,New,Remove,Set
Log Get
LogType Get
NetworkAdapter Get,New,Remove,Set
NicTeamingPolicy Get,Set
OSCustomizationNicMapping Get,New,Remove,Set
OSCustomizationSpec Get,New,Remove,Set
PassthroughDevice Add,Get,Remove
PowerCLIConfiguration Get,Set
PowerCLIVersion Get
ResourcePool Get,Move,New,Remove,Set
ScsiLun Get,Set
ScsiLunPath Get,Set
Snapshot Get,New,Remove,Set
Stat Get
StatInterval Get,New,Remove,Set
StatType Get
Task Get,Stop,Wait
Template Get,Move,New,Remove,Set
Tools Dismount,Mount,Update
UsbDevice Get,Remove
VApp Export,Get,Import,New,Remove,Set,Start,Stop
VICredentialStoreItem Get,New,Remove
VIEvent Get
View Get
VIObjectByVIView Get
VIPermission Get,New,Remove,Set
VIPrivilege Get
VIProperty New,Remove
VIRole Get,New,Remove,Set
VirtualPortGroup Get,New,Remove,Set
VirtualSwitch Get,New,Remove,Set
VIServer Connect,Disconnect
VM Get,Move,New,Remove,Restart,Set,Start,Stop,Suspend
VMGuest Get,Restart,Shutdown,Suspend
VMGuestFile Copy
VMGuestNetworkInterface Get,Set
VMGuestRoute Get,New,Remove,Set
VMHost Add,Get,Move,Remove,Restart,Set,Start,Stop,Suspend
VMHostAccount Get,New,Remove,Set
VMHostAdvancedConfiguration Get,Set
VMHostAvailableTimeZone Get
VMHostDiagnosticPartition Get,Set
VMHostFirewallDefaultPolicy Get,Set
VMHostFirewallException Get,Set
VMHostFirmware Get,Set
VMHostHba Get,Set
VMHostModule Get,Set
VMHostNetwork Get,Set
VMHostNetworkAdapter Get,New,Remove,Set
VmHostNtpServer Add,Get,Remove
VMHostPatch Get,Install
VMHostProfile Apply,Export,Get,Import,New,Remove,Set
VMHostProfileCompliance Test
VMHostRoute Get,New,Remove,Set
VMHostService Get,Restart,Set,Start,Stop
VMHostSnmp Get,Set,Test
VMHostStartPolicy Get,Set
VMHostStorage Get,Set
VMHostSysLogServer Get,Set
VMQuestion Get,Set
VMResourceConfiguration Get,Set
VMScript Invoke
VMStartPolicy Get,Set

VMware PowerShell Get-VIHumanReadablePath

An example of how to get the human readable path of an object in the VMware SDK. This is using PowerShell and requires that PowerCLI be installed, but should be easily converted to other languages.

Function Get-VIHumanReadablePath
{
    param
    (
        $target
    )
 
    try
    {
        if ($target.GetType().BaseType -ne [VMware.Vim.ManagedEntity])
        {
            $target = $target | Get-View -ErrorAction SilentlyContinue
        }
    }
    catch
    {
        $target = $null
    }
 
    if (!$target)
    {
        throw "Get-VIHumanReadablePath: Could not get the Managed Entity representation of -target"
    }
 
    $path = $target.Name
    while ($target.Parent)
    {
        $target = Get-View $target.Parent  
        $path = $target.Name + "/" + $path           
    }
 
    $path
}

Example usage

Get-VIHumanReadablePath (Get-Folder Linux)
Get-VIHumanReadablePath (Get-VM LinuxTemp01)
Get-VIHumanReadablePath (Get-VM LinuxTemp01 | Get-View)
Get-VIHumanReadablePath (Get-ResourcePool Prod)
Get-VIHumanReadablePath (Get-VM LinuxTemp01 | Get-ResourcePool)
Get-VIHumanReadablePath (Get-VMHost esx001.local)

Another Orchestrator/PowerShell hang issue

It has come to my attention that some times the scripts will still hang after using the trick from a previous post to fix an issue with standard input when running PowerShell in Orchestrator workflows. After further research there appears to be an issue with stderr hanging the scripts in a similar way to stdin. To be safe you should do something with the output from stderr (where error messages are sent).

You can do at least three things

//Throw it away with 2>NUL
command = new Command("cmd.exe /c powershell.exe -File c:\\orchestrator\\test.ps1 < NUL 2>NUL");
 
//Log it to a new file with 2> filename
command = new Command("cmd.exe /c powershell.exe -File c:\\orchestrator\\test.ps1 < NUL 2>c:\\orchestrator\\stderr.log");
 
//Send it wherever standard output goes using 2>&1
command = new Command("cmd.exe /c powershell.exe -File c:\\orchestrator\\estest.ps1 < NUL 2>&1");

For further reading on the topic of standard input, output, and error please see
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true

Running PowerShell in VMware Orchestrator – updated

Updated 7/29/2010 – I have added a new follow up post this post regarding another related hanging issue. Please make sure to check it out.

This is a copy of my comment in the VMware Communities, but some times the Google search results for items in this blog show up and the ones for the communities do not.

The original problem is that PowerShell scripts hang when running them in Orchestrator.

I have spent some time on this and have a way to make it work. For some reason when run this way the $input variable in Powershell is expecting a pipeline and I believe it just waits for pipelined input.

The $input variable is of type System.Management.Automation.Runspaces.Pipeline instead of the standard System.Collections.ArrayList+ArrayListEnumeratorSimple when running scripts. I have tried using the methods in the Pipeline class to clear things up to no avail. I have also tried using the input property on the Orchestrator Command class, but I could not get it to work. I am just getting started with Orchestrator though, so it may be my lack of knowledge.

As a workaround you can input NUL to the script or command using cmd.exe.

// Run a command
command = new Command("cmd /c powershell.exe -Command dir variable: >> c:\\orchestrator\\input.out < NUL");
command.execute(true);
 
//Run a script
command = new Command("cmd /c powershell.exe -File c:\\orchestrator\\input.ps1 < NUL");
command.execute(true);

Adding VMware PowerCLI to your standard PowerShell environment

In order to get access to PowerCLI when using another PowerShell shortcut or environment you can run the following commands which is what happens when you run the VMware provided shortcut.

# Adds the base cmdlets
Add-PSSnapin VMware.VimAutomation.Core
# Add the following if you want to do things with Update Manager
Add-PSSnapin VMware.VumAutomation
# This script adds some helper functions and sets the appearance. You can pick and choose parts of this file for a fully custom appearance.
. "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-VIToolkitEnvironment.ps1"

**UPDATE 2/7/2013**
As Paul noted in the comments, the new initialization script is called Initialize-PowerCLIEnvironment.ps1. Also, if you are on a 64 bit system the files will be in “Program Files (x86)”

Note on the last line that there is a space between the “.” and the path to the script. That space is very important as it means we are including or “dot sourcing” the file.

If you want this all to load every time you launch PowerShell you can add these commands to your profile startup scripts. This is a great place to add functions or aliases that you use all the time. The profile is run once when the PowerShell environment is launched.

PowerCLI Examples for VMUG Presentation 7/20/2010

These are some examples that I will be reviewing at an upcoming Central Ohio VMware User’s Group.

 
# List all VMs
Get-VM
 
# Get one VM
Get-VM ubuntu01
 
# Get VMs that match
Get-VM ubuntu*
 
# List VMs in a Datacenter
Get-Datacenter dc001 | Get-VM
 
# List VMs in a cluster
Get-Cluster cluster001 | Get-VM
 
# Get 2 CPU or larger VMs
Get-VM | Where-Object {$_.NumCPU -ge 2}
 
# Get 2 GB RAM or larger VMs
Get-VM | Where-Object {$_.MemoryMB -ge 2048}
 
# Getting information about what you can do
Get-VICommand
Get-Command
Get-Help Get-VM
Get-Member
Get-VM | Get-Member
 
# Save a report of VM CPU/MEM configuration information
Get-VM | Select-Object Name, NumCPU, MemoryMB | Export-Csv "VM_CPU_Memory_20100720.csv" -NoTypeInformation
 
# List VMs with connected CD-ROMs
Get-VM | Where-Object {$_ | Get-CDDrive | Where-Object {$_.ConnectionState.Connected}}
 
# Disconnect all connected CD-ROMs
Get-VM | Get-CDDrive | Where-Object {$_.ConnectionState.Connected} | Set-CDDrive -Connected $false -Confirm:$false
 
# Migrate a template to another host
Get-Template ubuntu | Set-Template -ToVM | Move-VM -Destination (Get-VMHost esx001.lab.local) | Set-VM -ToTemplate -Confirm:$false
 
# Report on Storage
Get-Datastore | Select-Object Name, FreeSpaceMB, CapacityMB | Export-Csv "Datastores_20100720.csv" -NoTypeInformation
 
# Storage VMotion ALL VMs from one LUN to another (All at the same time) COULD BE BAD
Get-Datastore "cla_nonrep_01" | Get-VM | Move-VM -Datastore (Get-Datastore "cla_nonrep_00")
 
# Storage VMotion ALL VMs from one LUN to another (One at a time)
Get-Datastore "cla_nonrep_01" | Get-VM | ForEach-Object {Move-VM -VM $_ -Datastore (Get-Datastore "cla_nonrep_00")}
 
# Set all limited CPU reservations to unlimted
Get-VM | Get-VMResourceConfiguration | Where-Object { $_.CpuLimitMhz -ne -1} | Set-VMResourceConfiguration -CpuLimitMhz $null
 
# Set all limited memory reservations to unlimited
Get-VM | Get-VMResourceConfiguration | Where-Object { $_.MemLimitMB -ne -1} | Set-VMResourceConfiguration -MemLimitMB $null
 
# Configure a new network on a host
Get-VirtualSwitch -VMHost esx003.lab.local -Name vSwitch0 | New-VirtualPortGroup -Name "VGT Test" -VLanId 4095
 
# Configure a new network on a cluster
Get-VirtualSwitch -VMHost (Get-Cluster cluster001 | Get-VMHost) -Name vSwitch0 | New-VirtualPortGroup -Name "VGT Test" -VLanId 4095
 
# Generate a diagnostic log bundle
Get-Log -VMHost esx001.lab.local -Bundle -DestinationPath c:\hostlogs
 
# List the entries in vmkwarning
(Get-Log -VMHost esx001.lab.local -Key vmkwarning).Entries
 
# Find something in a log
(Get-Log -VMHost esx001.lab.local -Key vmkernel).Entries | Select-String "Error"
 
# What logs are available?]
Get-LogType -VMHost esx001.lab.local
 
# Find VMs with snapshots (Pretty slow - could be optimized)
Get-VM | Where-Object {$_ | Get-Snapshot}
 
#Verify advanced settings
# http://wannemacher.us/?p=135
 
# Change advanced settings
# http://wannemacher.us/?p=104
 
# Change the root password across multiple hosts
# http://wannemacher.us/?p=304

Export and Import Customization Specs Using PowerCLI

Here are a couple of functions to help you export and import OS customization specs in vCenter. Be aware that if you do this between vCenters or the certificate changes then you will have to set any encrypted passwords to their correct value after the import.

These functions and the standard *-OSCustomizationSpec cmdlets should allow you to replicate your customization specs between multiple vCenters fairly easily.

Function Export-OSCustomizationSpec {
    param (
        [string]$specName,
        [string]$exportFile = "$specname.xml"
    )
    $csmgr = Get-View CustomizationSpecManager
 
    if ($csmgr.DoesCustomizationSpecExist($specName)) {
        $spec = $csmgr.GetCustomizationSpec($specName)
        $csmgr.CustomizationSpecItemToXml($spec) | Out-File $exportFile
    }
    else {
        throw "Spec $specName not found"
    }
}
 
Function Import-OSCustomizationSpec {
    param (
        [string]$importFile,
        [string]$specName #Use to change the spec name from that defined in the file
    )
 
    $specXml = Get-Content $importFile
    $csmgr = Get-View CustomizationSpecManager
    $spec = $csmgr.XmlToCustomizationSpecItem($specXml)
 
    # Change the name if a new one was given.
    if ($specName) {
        $spec.Info.Name = $specName
    }
 
    if ($csmgr.DoesCustomizationSpecExist($spec.Info.Name)) {
        throw "Spec $specName already exists."
    }
    else {
        $csmgr.CreateCustomizationSpec($spec)
    }
}