PowerShell

PowerCLI Move-Datastore Function

Moving datastores into folders via drag/drop can be painful. In some cases vCenter does not want to allow a drag from a long list. Here is a quick function to make moving via PowerCLI a little bit easier.

Function Move-Datastore {
    param (
        [VMware.VimAutomation.ViCore.Impl.V1.DatastoreManagement.VmfsDatastoreImpl[]]
            $datastore = $(throw "Datastore(s) must be provided."),
        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]
            $folder = $(throw "A destination folder must be provided.")
    )
 
    if ($folder.Type -ne "Datastore") {
        throw ("The specified folder is not a datastore folder.")
        exit
    }
 
    $dsList = @()
    foreach ($ds in $datastore) {
        $dsList += $ds.ID
    }
 
    $folder.ExtensionData.MoveIntoFolder($dsList)
}

Convenience Functions for Connecting to Multiple vCenters

In a large environment repeatedly connecting and disconnecting from groups of vCenters can be tedious so I created some helper functions and put them in my PowerShell profile.

Connect-VIServerGroup lab
Connect-VIServerGroup desktops
Disconnect-VIServerGroup lab
Function Connect-VIServerGroup {
	param (
		[String]$group = $(throw "A VI server group name must be specified.")
	)
 
	Connect-VIServer -Server (Get-VIServerList $group)
}
 
Function Disconnect-VIServerGroup {
	param (
		[String]$group = $(throw "A VI server group name must be specified.")
	)
 
	Disconnect-VIServer -Server (Get-VIServerList $group) -Confirm:$false
}
 
Function Get-VIServerList {
	param (
		[String]$group = $(throw "A VI server group name must be specified.")
	)
 
	switch ($group) {
		"lab" {"vclab01.local", "vclab02.local"}
		"servers" {"vc001.local", "vc002.local", "vc003.local", "vc004.local"}
		"desktops" {"vc005.local", "vc006.local", "vc007.local", "vc008.local"}
		default {throw "No VI server group named $group found."}
	}
}

PowerShell: Alternate script behavior when dot sourced vs run directly

I use dot sourcing in my PowerShell scripts to reuse functions* and sometimes I want different behavior if they are included (dot sourced) or run directly. This concept is used in Python to provide an easy way to run tests against the code when run directly but not when it is imported.

You are not restricted to running tests using this approach, but I think that automated testing is useful so that is the example I provide below.
(more…)

VMware PowerCLI 5 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
DatastoreCluster Get
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,Move,New,Remove,Set,Start,Stop
VIAccount Get
VICredentialStoreItem Get,New,Remove
VIEvent Get
View Get
VIObjectByVIView Get
VIPermission Get,New,Remove,Set
VIPrivilege Get
VIProperty Get,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
VMHostAuthentication 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
VMHostProfileRequiredInput Get
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

Simple XML output of a data object

I am doing some data collection using PowerShell and the output needs to be a simple XML document string.

The built in cmdlets do a great job when persisting data, but they produce some fairly complicated XML that provides more detail on object types than I can use.

Here is a single function to take a PSObject based data object and turn it into XML. I have also included a test function to show an example of building the data object.

 
Function Convert-CustomObjectToXml {
<#
.SYNOPSIS
 
Outputs a human readable simple text XML representation of a simple PS object.
 
.PARAMETER object
 
The input object to inspect and dump.
 
.PARAMETER depth
 
The number of levels deep to dump. Defaults to 1.
 
.PARAMETER rootEl
 
The name of the root element in the document. Defaults to "root"
 
.PARAMETER indentString
 
The string used to indent each level of XML. Defaults to two spaces.
Set to "" to remove indentation.
 
.DESCRIPTION
 
Outputs a human readable simple text XML representation of a simple PS object.
 
A PSObject with member types of NoteProperty will be dumped to XML.  Only
nested PSObjects up to the depth specified will be searched. All other
note properties will be ouput using their strings values.
 
The output consists of node with property names and text nodes containing the
proprty value.
 
#>
	param (
		[PSCustomObject]$object,
		[Int32]$depth = 1,
		[String]$rootEl = "root",
		[String]$indentString = "  ",
		[Int32]$indent = 1,
		[switch]$isRoot = $true
	)
 
	# Output the root element opening tag
	if ($isRoot) {
		"<{0}>" -f $rootEl
	}
 
	# Iterate through all of the note properties in the object.
	foreach ($prop in (Get-Member -InputObject $object -MemberType NoteProperty)) {
		$child = $object.($prop.Name)
 
		# Check if the property is an object and we want to dig into it
		if ($child.GetType().Name -eq "PSCustomObject" -and $depth -gt 1) {
			"{0}<{1}>" -f ($indentString * $indent), $prop.Name
				Convert-CustomObjectToXml $child -isRoot:$false -indent ($indent + 1) -depth ($depth - 1) -indentString $indentString
			"{0}</{1}>" -f ($indentString * $indent), $prop.Name
		}
		else {
			# output the element or elements in the case of an array
			foreach ($element in $child) {
				"{0}<{1}>{2}</{1}>" -f ($indentString * $indent), $prop.Name, $element
			}
		}
	}
 
	# Output the root element closing tag
	if ($isRoot) {
		"</{0}>" -f $rootEl
	}
}
 
Function Test-Convert-CustomObjectToXml {
 
	# Create an example object and then try to dump it to the screen.
	$a = New-Object PSObject
	$a | Add-Member -MemberType NoteProperty -Name "CPU" -Value 4
	$a | Add-Member -MemberType NoteProperty -Name "Memory" -Value 800
	$a | Add-Member -MemberType NoteProperty -Name "NICs" -Value (New-Object PSObject)
	$a.NICs | Add-Member -MemberType NoteProperty -Name "vmnic0" -Value "1000"
	$a.NICs | Add-Member -MemberType NoteProperty -Name "vmnic1" -Value "1000"
	$a.NICs | Add-Member -MemberType NoteProperty -Name "vmnic2" -Value "1000"
	$a.NICs | Add-Member -MemberType NoteProperty -Name "vmnic3" -Value "1000"
	$a | Add-Member -MemberType NoteProperty -Name "VMs" -Value (New-Object PSObject)
	$a.VMs | Add-Member -MemberType NoteProperty -Name "VM" -Value @()
	$a.VMs.VM += "foo"
	$a.VMs.VM += "bar"
	$a.VMs.VM += "bash"
	$a.VMs.VM += "bang"
 
	Convert-CustomObjectToXml $a
 
	Convert-CustomObjectToXml $a -depth 10 -rootEl "config"
}

Some sample output.

<root>
  <CPU>4</CPU>
  <Memory>800</Memory>
  <NICs>@{vmnic0=1000; vmnic1=1000; vmnic2=1000; vmnic3=1000}</NICs>
  <VMs>@{VM=System.Object[]}</VMs>
</root>
<config>
  <CPU>4</CPU>
  <Memory>800</Memory>
  <NICs>
    <vmnic0>1000</vmnic0>
    <vmnic1>1000</vmnic1>
    <vmnic2>1000</vmnic2>
    <vmnic3>1000</vmnic3>
  </NICs>
  <VMs>
    <VM>foo</VM>
    <VM>bar</VM>
    <VM>bash</VM>
    <VM>bang</VM>
  </VMs>
</config>

PowerShell Asynchronous Job Queueing

Here is some sample code to have a variable size work queue for asynchronous jobs in PowerShell. The sample code uses Start-Job, but it was written as a skeleton to be able to run multiple PowerCLI tasks at once.

The variable length is beneficial in case the work should be split up, but there is a chance of overwhelming the system if too many concurrent jobs are started at once.

Write-Host "Script Starting."
 
$concurrentTasks = 3 # How many tasks can run at once.
$waitTime = 500 # Duration in ms the script waits to check for job status changes.
 
# $jobs holds pertinent job information. This is a test script so these are
# just simple values to track script progress.
$jobs = @("a", "b", "c", "d", "e", "f", "g")
$jobIndex = 0 #Which job is up for running
$workItems = @{} # Items being worked on
$workComplete = $false # Is the script done with what it needs to do?
 
while (!$workComplete) {
	# Process any finished jobs.
	foreach ($key in @() + $workItems.Keys) {
		# Write-Host "Checking job $key."
		if ($workItems[$key].State -eq "Completed") {
			"$key is done."
			$result = Receive-Job $workItems[$key]
			$workItems.Remove($key)
			"Result: $result"
		}
	}
 
	# Start new jobs if there are open slots.
	while (($workItems.Count -lt $concurrentTasks) -and 
		   ($jobIndex -lt $jobs.Length)) {
			# These jobs don't do anything other than wait a variable amount of time
			# and print an output message.
			$workTime = Get-Random -Minimum 2000 -Maximum 10000
			$job = $jobs[$jobIndex]
			"Starting job {0}." -f $job
			$workItems[$job] = Start-Job -ArgumentList $workTime, $job -ScriptBlock {Start-Sleep -Milliseconds $args[0]; "{0} processed." -f $args[1]}
			$jobIndex += 1
	}
 
	# If all jobs have been processed we are done.
	if ($jobIndex -eq $jobs.Length -and $workItems.Count -eq 0) {
		$workComplete = $true
	}
 
	# Wait between status checks
	Start-Sleep -Milliseconds $waitTime
}
 
Write-Host "Script Finished."