Scripting

VMware PowerCLI 4.1.1 Cmdlets by Noun

Generated using this post.

Noun Verbs
AdvancedSetting Get,New,Remove,Set
AlarmAction Get,New,Remove
AlarmActionTrigger Get,New,Remove
AlarmDefinition Get,Set
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
EsxCli Get
EsxTop Get
FloppyDrive Get,New,Remove,Set
Folder Get,Move,New,Remove,Set
HAPrimaryVMHost Get
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
ScsiController Get,New,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,Wait
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
VMHost Add,Get,Move,Remove,Restart,Set,Start,Stop,Suspend
VMHostAccount Get,New,Remove,Set
VMHostAdvancedConfiguration Get,Set
VMHostAvailableTimeZone Get
VMHostDiagnosticPartition Get,Set
VMHostDisk Get
VMHostDiskPartition Format,Get
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

Quick and dirty PowerPath/VE output parser

Here is a quick and dirty PowerShell script to parse the output of the rpowermt command used to manage PowerPath/VE on ESX (for EMC arrays). I wrote the code quickly to solve a particular problem, but if I get requests I could extend it to parse the rest of the output and do so in a little more robust fashion.

Why do this? I am in the middle of migrations between frames and I needed an easy way to determine what needed moved when the storage admin said move all LUNs from CLARiiON XXXX to the new LUNs on YYYY – and make sure to move LUN 41 to LUN 88.

By parsing the output of rpowermt I could more easily determine the ID of the LUNs they indicated and map that to the extent properties of my datastores to determine what needed to move.

Two step usage:

  1. rpowermt host=esx001 display dev=all > esx001_lundata.txt
  2. $lunInfo = .\SimplePowerVeParse esx001_lundata.txt

Alternate ways of accomplishing the same thing:

  1. The Storage Viewer plugin from EMC would be helpful in determining this from the GUI, but due to political reasons this is not yet deployed in production.
  2. I originally wanted to try and talk to the CIM provider for PowerPath, but quickly found that the Get-WSManInstance cmdlet’s authentication assumptions were very Windows centric.

The script (more…)

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)

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);

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)
    }
}

Notify All Active vSphere Users (PowerCLI version)

Steve Jin recently posted How to Notify All the Active vSphere Users on his DoubleCloud blog. Below are some functions to make this easy to do via PowerCLI.

Function Get-VIServiceMessage {
    $sessionManager = Get-View SessionManager
    $sessionManager.Message
}
 
Function Set-VIServiceMessage {
    param (
        [String]$message = $(throw "Must specify a message.")
    )
 
    $sessionManager = Get-View SessionManager
    $sessionManager.UpdateServiceMessage($message)
}
 
Function Remove-VIServiceMessage {
    Set-ServiceMessage("")
}

Summarize PowerCLI Cmdlets by Noun

Here is some simple code to generate a reference list of the PowerCLI cmdlet objects(nouns) and what actions(verbs) you can perform on them.

This can come in handy for people new to PowerCLI to show them what the cmdlets will handle for them.

$commandTable = @{}
$commandList = Get-Command -Module VMware.VimAutomation.Core -CommandType Cmdlet
 
foreach ($command in $commandList) {
 
    if (!$commandTable.ContainsKey($command.Noun)) {
        $commandTable[$command.Noun] = @()
    }
 
    $commandTable[$command.Noun] += $command.Verb
}
 
foreach ($command in $commandTable.Keys | Sort-Object) {
    $verbs = $commandTable[$command] | Sort-Object
    $command | Select-Object @{Name="Noun"; Expression={$command}}, 
                                 @{Name="Verbs"; Expression={[String]::Join(",", $verbs)}}
}

Here is the output for PowerCLI version 4 update 1.
(more…)