Updated: Get VMware tools versions by ESXi host version – a PowerCLI function to map tools version codes to readable version numbers

Quite some time ago I created a PowerCLI function to help me determine VMware Tools versions of queried VMs using PowerCLI. The tools version is returned as a 4 digit number by the vSphere API, and subsequently, so does PowerCLI. This makes determining VMware Tools versions at a glance, a bit of a hassle.

The original function was able to output Tools versions up to ESXi 4.1 u1 or u2, and this week was the first time I had a good use case for this script. I needed more up to date mappings, so I have updated the function to work with VMware tools versions all the way up to ESXi 5.5 now.

Here is the latest script:

# Mapping file found at: http://packages.vmware.com/tools/versions

Function Get-VMToolsMapped() {

 Get-VMToolsMapped -VM MYVMNAME

.EXAMPLE
PS F:\> Get-VMToolsMapped MYVMNAME

.EXAMPLE
PS F:\> Get-VM | Get-VMToolsMapped

.EXAMPLE
PS F:\> Get-Cluster "CLUSTERNAME" | Get-VM | Get-VMToolsMapped

.LINK
http://www.shogan.co.uk

.NOTES
Created by: Sean Duffy
Date: 05/02/2014
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Specify the VM name you would like to query VMware Tools info for.",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]
$VM
)

process {

$Report = @()
New-VIProperty -Name ToolsVersion -ObjectType VirtualMachine -ValueFromExtensionProperty 'config.tools.ToolsVersion' -Force

$VMInfo = Get-VM $VM | Select Name, ToolsVersion
Switch ($VMInfo.ToolsVersion) {
	9344 {$ESXMapping = "esx/5.5"}
	9226 {$ESXMapping = "esx/5.1u2"}
	9221 {$ESXMapping = "esx/5.1u1"}
	9217 {$ESXMapping = "esx/5.1"}
	9216 {$ESXMapping = "esx/5.1"}
	8396 {$ESXMapping = "esx/5.0u3"}
	8395 {$ESXMapping = "esx/5.0u3"}
	8394 {$ESXMapping = "esx/5.0u2"}
	8389 {$ESXMapping = "esx/5.0u1"}
	8384 {$ESXMapping = "esx/5.0"}
	8307 {$ESXMapping = "esx/4.1u3"} 
	8306 {$ESXMapping = "esx/4.1u3"} 
	8305 {$ESXMapping = "esx/4.1u3"} 
	8300 {$ESXMapping = "esx/4.1u2"}
	8295 {$ESXMapping = "esx/4.1u1"}
	8290 {$ESXMapping = "esx/4.1"}
	8289 {$ESXMapping = "esx/4.1"}
	8288 {$ESXMapping = "esx/4.1"}
	8196 {$ESXMapping = "esx/4.0u4 or esx/4.0u3"}
	8195 {$ESXMapping = "esx/4.0u2"}
	8194 {$ESXMapping = "esx/4.0u1"}
	8193 {$ESXMapping = "esx/4.0"}
	7304 {$ESXMapping = "esx/3.5u5"}
	7303 {$ESXMapping = "esx/3.5u4"}
	7302 {$ESXMapping = "esx/3.5u3"}
	default {$ESXMapping = "Unknown"}
	}

$row = New-Object -Type PSObject -Property @{
   		Name = $VMInfo.Name
		ToolsVersion = $VMInfo.ToolsVersion
		ESXMapping = $ESXMapping
	}
$Report += $row
return $Report

}
}

If you have any issues copying and pasting the script from this post, here is a direct download you can use too:

[download id=”28″]

 

A function to lookup Host System friendly name by MoRef using PowerCLI

In a recent blog post, I showed a simple method of outputting a list of hosts with their friendly names, as well as their MoRef (Managed Object Reference) names alongside eachother, enabling you to match up which host belongs to which MoRef. I wanted to take that a little further, with a function that is able to return the friendly name of a host’s MoRef that is input into the function. I have used this is a larger reporting script, where I can only get the MoRef of a host via it’s property within a cluster object. Basically, I look for any Failover hosts (admission control policy), which is an array, and the hosts are listed as indexed objects of this array. They are also only displayed as MoRef names, so at this point, instead of inserting the MoRef into my results, I insert the MoRef into this function, return the friendly name, and input this instead. Which allows the person reading the report to easily identify the host! $cluster.ExtensionData.Configuration.DasConfig.AdmissionControlPolicy.FailoverHosts <- In this example, $cluster is a particular cluster using the “specify a failover host” policy, and “FailoverHosts” is the array, with each object within containing a host MoRef. For example FailoverHosts[0].Value would be one instance, and may equate to “HostSystem-host-28” for example.   So here is the function. It takes two mandatory parameters: -MoRef (the MoRef of the host in question of course), and -Cluster (the name of the Cluster to do the lookup in) – the function loops through each host in this cluster to look for a host that matches the input MoRef.

Function Get-VMHostByMoRef() {

<#
.SYNOPSIS
Fetches host name by input MoRef and Cluster to look in

.DESCRIPTION
Fetches host name by input MoRef and Cluster to look in

.PARAMETER MoRef
The MoRef of the host system

.PARAMETER Cluster
The name of the cluster to do the lookup in

.EXAMPLE
PS F:\> Get-VMHostByMoRef -MoRef HostSystem-host-28 -Cluster MyCluster01

.LINK
http://www.shogan.co.uk

.NOTES
Created by: Sean Duffy
Date: 22/02/2013
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Specify the Host MoRef name you would like to query for it's friendly name.",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][String]$MoRef,[Parameter(Position=1,Mandatory=$true,HelpMessage="Specify the Cluster to search hosts in.",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][String]$Cluster
)

process {

$AllHosts = Get-Cluster $Cluster | Get-VMHost
$thehost = $AllHosts | Where {$_.ExtensionData.MoRef -match $MoRef} | Select-Object -Property Name

return $thehost

}
}

Here is a quick sample of the output when called directly from the PowerCLI prompt (note the MoRef of “host-22” used to find the real host name of “esxi02.homelab.local”: Hopefully this may be of use to some – add it to your PowerCLI script/function toolkit or throw it into your PowerShell $profile for easy access in the future!

Using plink to modify ESXi host configuration files via SSH from a PowerCLI script

I am a big advocate of automation and saving time with a good script. Whenever I can find a task that is fairly lengthy, and is likely to be repeated in future, I always consider scripting it. There are many way to configure an ESXi host when it comes to writing build or automation scripts. In fact, I often feel we are quite spoilt for choice. Here are just some of the tools we have available to use:

  • PowerCLI
  • esxcli
  • vMA
  • vCLI

I was working on a build configuration script the other day using PowerCLI and found the need to edit some configuration files on the hosts. I wanted to edit the configuration file /etc/vmware/config during the execution of a single PowerCLI script without needing to stop the script or have an additional step to do myself. The following is what I came up with to achieve this:

  • Configure host as normal using PowerCLI
  • Use PowerCLI to start SSH service on host
  • execute plink script to connect to host, run command via SSH, then disconnect
  • Use PowerCLI to stop SSH service on host
  • Continue with rest of PowerCLI script

 

Plink is a command line connection tool – essentially a command line version of PuTTy. You can call it from dos prompt and issue it with a single, (or list) of commands to run once connected to a specified host. You can download Plink over here.

 

So without further ado, let’s take a look at the script as I described above.

# At start of our script we ask for the host's IP or name (this could be automated if you like)
$hostIP = Read-Host "Enter ESX host IP/dns name: "
$vmhost = Get-VMHost $hostIP

# Start the SSH service
$sshService = Get-VmHostService -VMHost $vmhost | Where { $_.Key -eq “TSM-SSH”}
Start-VMHostService -HostService $sshService -Confirm:$false

# Use SSH / plink to configure host with some additional script
cmd /c "plink.exe -ssh -pw HOSTROOTPASSWORD -noagent -m commands.txt root@$hostIP"

# Stop SSH service
Stop-VMHostService -HostService $sshService -Confirm:$false

 

As you can see, we start off by asking for the host IP or name, this is the only bit of manual input, but even this could be automated. The script then finds the SSH service on the host, and starts it. After this, the script calls the plink.exe file via cmd /c and connects using the root user@ the host’s IP as we entered at the beginning of the script over SSH. Plink is pointed to a commands.txt file (previously placed in the script execution folder), which contains the actual lines of bash script to be executed on the ESXi host via SSH.

Here is the content of the commands.txt file that I refer plink.exe to use (as an example, this bit of script enables copy/paste operations on all VMs running on this host in the guest OS’ console, as per VMware KB 1026437), but could contain any other commands you wish to execute on the ESXi host over SSH.

echo 'isolation.tools.copy.disable="FALSE"' >> /etc/vmware/config
echo 'isolation.tools.paste.disable="FALSE"' >> /etc/vmware/config

 

* Note two very useful techniques show by Alan in the comments section below, showing how to automatically download plink.exe if it is not available when the script is run, and also how to accept the SSH fingerprint key request by piping Y to plink.exe via the script – check out Alan’s blog post here for more detail.

Get Virtual Machine Inventory from a Hyper-V Failover Cluster using PowerShell

A colleague was asking around for a PowerShell script that would fetch some inventory data for VMs on a Hyper-V cluster the other day. Not knowing too much about Hyper-V and having only ever briefly looked at what was out there in terms of PowerShell cmdlets for managing Hyper-V, I decided to dive in tonight after I got home.

 

Here is a function that will fetch Inventory data for all VMs in a specified Failover Cluster. This is what it fetches:

  • VM Name
  • VM CPU Count
  • VM CPU Socket Count
  • VM Memory configuration
  • VM State (Up or Down)
  • Cluster Name the VM resides on
  • Hyper-V Host name the VM resides on
  • Network Virtual Switch Name
  • NIC Mac Address
  • Total VHD file size in MB
  • Total VHD Count

 

Being a function, you can pipe in the name of the cluster you want, for example Get-Cluster | Get-HyperVInventory. Or you could do Get-HyperVInventory -ClusterName “ExampleClusterName”. You could also send it to an HTML Report by piping it to “ConvertTo-HTML | Out-File example.html”

Download here, or copy it out from the script block below:
[download id=”15″]
 

# Requires: Imported HyperV PowerShell module (http://pshyperv.codeplex.com/releases/view/62842)
# Requires: Import-Module FailoverClusters
# Requires: Running PowerShell as Administrator in order to properly import the above modules

function Get-HyperVInventory {
<#
.SYNOPSIS
Fetches Hyper-V VM Inventory from a specified Hyper-V Failover cluster

.DESCRIPTION
Fetches Hyper-V VM Inventory from a specified Hyper-V Failover cluster

.PARAMETER ClusterName
The Name of the Hyper-V Failover Cluster to inspect

.EXAMPLE
PS F:\> Get-HyperVInventory -ClusterName "dev-cluster1"

.EXAMPLE
PS F:\> Get-Cluster | Get-HyperVInventory

.LINK
http://www.shogan.co.uk

.NOTES
Created by: Sean Duffy
Date: 09/07/2012
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the Cluster to fetch inventory from",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[System.String]
$ClusterName
)

process {

$Report = @()

$Cluster = Get-Cluster -Name $ClusterName
$HVHosts = $Cluster | Get-ClusterNode

foreach ($HVHost in $HVHosts) {
$VMs = Get-VM -Server $HVHost
foreach ($VM in $VMs) {
[long]$TotalVHDSize = 0
$VHDCount = 0
$VMName = $VM.VMElementName
$VMMemory = $VM | Get-VMMemory
$CPUCount = $VM | Get-VMCPUCount
$NetSwitch = $VM | Get-VMNIC
$NetMacAdd = $VM | Get-VMNIC
# VM Disk Info
$VHDDisks = $VM | Get-VMDisk | Where { $_.DiskName -like "Hard Disk Image" }
foreach ($disk in $VHDDisks) {
$VHDInfo = Get-VHDInfo -VHDPaths $disk.DiskImage
$TotalVHDSize = $TotalVHDSize + $VHDInfo.FileSize
$VHDCount += 1
}
$TotalVHDSize = $TotalVHDSize/1024/1024
$row = New-Object -Type PSObject -Property @{
Cluster = $Cluster.Name
VMName = $VMName
VMMemory = $VMMemory.VirtualQuantity
CPUCount = $CPUCount.VirtualQuantity
CPUSocketCount = $CPUCount.SocketCount
NetSwitch = $NetSwitch.SwitchName
NetMACAdd = $NetMacAdd.Address
HostName = $HVHost.Name
VMState = $HVHost.State
TotalVMDiskSizeMB = $TotalVHDSize
TotalVMDiskCount = $VHDCount
} ## end New-Object
$Report += $row
}
}
return $Report

}
}

 

Example use cases – load the function into your PowerShell session, or place it in your $profile for easy access in future, and run the following:

# Example 1
Get-HyperVInventory -ClusterName "mycluster1"
# Example 2
Get-Cluster | Get-HyperVInventory
# Example 3
Get-HyperVInventory -ClusterName "mycluster1" | ConvertTo-HTML | Out-File C:\Report.html

 

The function includes help text and examples, so you can also issue the normal “Get-Help Get-HyperVInventory” or “Get-Help Get-HyperVInventory -Examples”. It is by no means perfect and could do with some improvements, for example if there is more than one Virtual Switch Network associated with a VM these would be listed in a row multiple times for each. Feel free to suggest any improvements or changes in the comments.

 

Changing Registry entries on multiple systems with PowerShell and Remoting

 

A few weeks ago, a colleague asked if I knew of a way to script the change or modification of the Registered Owner / Organization information on a Windows Server system (2003 or 2008). I knew that this could be achieved with PowerShell and had some initial ideas, so I spent a few minutes whipping up the script below.

For this to work, you should ideally have all systems on the same Windows Domain and have enabled PowerShell remoting on each system that needs to be changed. Of course you could also just run the script on a single workstation/server on its own without the need for PSRemoting.

 

# On all remote machines that need their info changed
Set-ExecutionPolicy RemoteSigned
Enable-PSRemoting # Say yes to all prompts
#region This part only needed if machines do not belong to the same domain...
# Note: This can be a security risk, only use if you are sure you want to allow any host as a trusted host. (e.g. fine for lab environments)
cd wsman::localhost\client
Set-Item .\TrustedHosts * # Say yes to all prompts
#endregion
# Run on your management machine/machine you are using to update all others...
$computers = @("SERVER1","SERVER2","SERVER3")

foreach ($computer in $computers) {
    Enter-PSSession $computer
    cd 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion'
    Set-ItemProperty -Path . -Name "RegisteredOwner" -Value "Auth User"
    Set-ItemProperty -Path . -Name "RegisteredOrganization" -Value "Lab"
    Exit-PSSession
}

 

So the above should update your registered owner and organization details for each server listed in the $computers array. (Specify your own host names here). The above script should be easy enough to modify if you are looking to change other registry entries. Finally, don’t forget that you should always be careful when updating registry, especially via script – make sure you have backups!