PowerCLI – Fetch Interesting stats or configuration for a list of VMs

Now and then I find that I need to retrieve some useful information from a variety of VMs, this usually involves me doing a Get-VM with some selections and criteria to search for. However sometimes the information I require about a VM is listed in the advanced configuration and not as easy to get to with a single cmdlet. I thought it would be really handy to have a PowerCLI function that would easily pull the useful information out for me and summarise it for any given VM or set of VMs.

 

With that said, I recently read a great blog post by Jonathan Medd (Basic VMware Cluster Compatibility Check), and after reading it I thought it would be a great idea to create a set of functions that provide me with the information I often use. To start, I thought I would do a function that lists the most useful or common information about VMs that I often search for. As well as speeding up the process of retrieving information about VMs, I thought it would also be good PS/PowerCLI practise for me to write more functions. The reason being that I often tend to do PowerCLI reporting scripts rather than actual functions that accept input from the pipeline or other parameters. Below is my function to collect some useful information about Virtual Machines – you can specify a VM with the -VM parameter or pipe a list of VMs to it, using Get-VM | Get-VMUsefulStats. Jonathan’s post also had an interesting section about the order in which output is displayed. You’ll need to pipe the output to Select-Object to change the order the information is fed back in, otherwise it will list the information in the default order. This is not really a problem anyway, just good to know if you are fussy about the order in which the output comes back in!)

 

So, here is the first function (Get-VMUsefulStats):

 

[download id=”7″]

 

function Get-VMUsefulStats {
<#
.SYNOPSIS
Fetches interesting or useful stats about VMware Virtual Machines

.DESCRIPTION
Fetches interesting or useful stats about VMware Virtual Machines

.PARAMETER VM
The Name of the Virtual Machine to fetch information about

.EXAMPLE
PS F:\> Get-VMUsefulStats -VM FS01

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

.EXAMPLE
PS F:\> Get-VM | Get-VMUsefulStats | Where {$_.Name -match "FS"}

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

.NOTES
Created by: Sean Duffy
Date: 18/01/2012
#>

[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,HelpMessage="Name of the VM to fetch stats about",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[System.String]
$VMName
)

process {

$VM = Get-VM $VMName

$VMHardwareVersion = $VM.Version
$VMGuestOS = $VM.OSName
$VMvCPUCount = $VM.NumCpu
$VMMemShare = ($VM.ExtensionData.Config.ExtraConfig | Where {$_.Key -eq "sched.mem.pshare.enable"}).Value
$VMMemoryMB = $VM.MemoryMB
$VMMemReservation = $VM.ExtensionData.ResourceConfig.MemoryAllocation.Reservation
$VMUsedSpace = [Math]::Round($VM.UsedSpaceGB,2)
$VMProvisionedSpace = [Math]::Round($VM.ProvisionedSpaceGB,2)
$VMPowerState = $VM.PowerState

New-Object -TypeName PSObject -Property @{
Name = $VMName
HW = $VMHardwareVersion
VMGuestOS = $VMGuestOS
vCPUCount = $VMvCPUCount
MemoryMB = $VMMemoryMB
MemoryReservation = $VMMemReservation
MemSharing = $VMMemShare
UsedSpaceGB = $VMUsedSpace
ProvisionedGB = $VMProvisionedSpace
PowerState = $VMPowerState
}
}
}

 

You can use the cmdlet to very easily retrieve information about a single VM or list of VMs. Examples:

 

Get-VMUsefulStats -VM NOOBS-VC01

Get-VM | Get-VMUsefulStats

 

To format the output in a neat table, pipe the above to Format-Table (ft) like so:

 

Get-VM | Get-VMUsefulStats | ft

 

The “MemShare” value is interesting – it is something I was specifically interested in, as some VMs I have worked with in the past have needed memory sharing to be specifically disabled, and this is something that needs to be changed with an advanced parameter on the VM. Therefore most (default) VMs will not have this entry at all and will appear blank in the output. (the parameter I am referring to for those interested is sched.mem.pshare.enable). Of course this most likely won’t be of any use to you, so feel free to omit this bit from the function, or feel free to customise the function to return information useful to your VMware deployment VMs. Here is an example of the output for one VM.

 

 

Anyway, I hope someone finds this useful, and please do let me know if you think of any improvements or better way of achieving a certain result.

 

Get vCenter User Sessions and Idle times with PowerCLI

Today I was looking into a small “nice to have” notification system for users that had left their vSphere clients open and logged into vCenter. I found this great bit of script to list currently logged in users over at blog.vmpros.nl and thought I would expand on this in my own way to generate a handy list of logged in users and their current idle time – similar to the way the “Sessions” tab in the vSphere client displays user session information. When I got home this evening I expanded on the original script from vmpros.nl to create the following:

 

$Now = Get-Date
$Report = @()
$svcRef = new-object VMware.Vim.ManagedObjectReference
$svcRef.Type = "ServiceInstance"
$svcRef.Value = "ServiceInstance"
$serviceInstance = get-view $svcRef
$sessMgr = get-view $serviceInstance.Content.sessionManager
foreach ($sess in $sessMgr.SessionList){
   $time = $Now - $sess.LastActiveTime
   # Our time calculation returns a TimeSpan object instead of DateTime, therefore formatting needs to be done as follows:
   $SessionIdleTime = '{0:00}:{1:00}:{2:00}' -f $time.Hours, $time.Minutes, $time.Seconds
   $row = New-Object -Type PSObject -Property @{
   		Name = $sess.UserName
		LoginTime = $sess.LoginTime
		IdleTime = $SessionIdleTime
	} ## end New-Object
	$Report += $row
}
$Report

 

[download id=”6″]

 

Here is an example of the output of the script:

 

Using this bit of PowerCLI script, it should be easy for you to create your own notification system based on user session idle time, or some functionality that would disconnect idle users. Let me know if you do improve on the above, or if you have any other suggestions.

 

Powershell – Check Free Memory script

 

Here’s a quick script I did using Powershell to check your free memory and report back the amount in MB and GB.

 

$freemem = Get-WmiObject -Class Win32_OperatingSystem

# Display free memory on PC/Server
"---------FREE MEMORY CHECK----------"
""
"System Name     : {0}" -f $freemem.csname
"Free Memory (MB): {0}" -f ([math]::round($freemem.FreePhysicalMemory / 1024, 2))
"Free Memory (GB): {0}" -f ([math]::round(($freemem.FreePhysicalMemory / 1024 / 1024), 2))
""
"------------------------------------"

Download the script here

 

The figure is determined and held in the $freemem variable. After that we simply output two lines to show the amount in MB and GB. We use a simple function to divide the figure by 1024 and round it off, displaying the result with two decimal places. The figure needs to be divided by 1024 as the variable holds the amount in Kilobytes (KB), therefore to determine Megabytes (MB), we divide by 1024. The second figure for GB requires one more division.

 

 

 

More PowerCLI basics – Host operations

 

On my quest to learn more about PowerCLI, I have been playing around with some more cmdlets in my lab. As a simple task, I have figured out how to tell ESX or ESXi hosts to enter and exit maintenance mode. Here’s how we do this. First of all ensure you are connected to your vCenter server instance using Connect-VIServer ServerName.

 

Enter maintenance mode:

Set-VMHost ESXi-01.noobs.local -State "Maintenance"

 

Exit maintenance mode:

Set-VMHost ESXi-01.noobs.local -State "Connected"

 

Set host to “disconnected” state:

Set-VMHost ESXi-01.noobs.local -State "Disconnected"

 

So now that we know the basics of setting the state of a VMware host, how about we get slightly more technical and perform one of the above operations on a bunch of hosts in one go? Powershell / PowerCLI is all about automation after all! Note that in the following script, I have also include a simple “if / else” statement to prompt the user running the script manually as we are about to send all ESX(i) hosts into maintenance mode! Use this at your own risk of course, it is just for demonstration purposes. You may want to modify to select hosts to enter maintenance mode on certain criteria. For example, all hosts in a particular cluster, or all hosts with a certain property. Here is the script I would use to perform the operation on all the ESX(i) hosts found in vCenter:

 

$VCServer = “yourvcservername”
Connect-VIServer $VCServer
$confirm = Read-Host “Are you sure you want all hosts to enter maintenance mode? (type yes to continue) “
if ($confirm -eq "yes")
{
	Get-VMHost | Set-VMHost -State "Maintenance"
}
else
{
	"Script aborted (you didn't confirm by typing yes)"
}

 

Once the script is executed, you should get a progress indicator whilst hosts are being dealt with. Afterwards you’ll get some output from each host listing its relevant Connection Status and statistics. Like so:

 

In the above example, we set some variables, and use some basic logic checking with an IF ELSE statement and an equal to (-eq) operator. We also see how to perform a few operations on ESX or ESXi hosts. I hope this helps anyone starting out with PowerCLI. Please do leave any comments, suggestions or improvements in the comments section!

 

PowerCLI – checking for snapshots on VMs and emailing the report back

Checking for any snapshots running on VMs in various clusters can be quite repetitive if done manually, looking through vCenter at each of your VMs. In the clusters I work with there are a LOT of VMs to check, and naturally I wanted to automate this process. Sure, I could rely on the vCenter alarms for snapshot size warning, but these are not completely reliable, as they only alert me when snapshots start growing large in size. I wanted something that would alert me to the presence of a snapshot regardless of its size. I therefore set about learning the basics of PowerCLI (as you can see in my last post) and searched around for some sample cmdlets that would help me retrieve a list of VMs with snapshots on them.

 

So here is the end result of running this snapshot checking script. It uses powershell cmdlets to generate an HTML email and sends it across to the address you specify. You will of course need to ensure you can connect out on port 25 for mail and have authentication on your mail server (or being sending from and to a domain hosted on your mail server (i.e. connecting to relay mail internally). Enter your mail server, to, and from details in the script to customise it. You’ll also need to authenticate with your vCenter server before running the script of course – you could use a cmdlet in the script to do this automatically. I have just been manually authenticating for now as I have not yet deployed this in production and have just been testing.

 

 

So here is the all important PowerCLI script!

 

#These are the properties assigned to the HTML table via the ConvertTo-HTML cmdlet - this is used to liven up the report and make it a bit easier on the eyes!

$tableProperties = "<style>"
$tableProperties = $tableProperties + "TABLE{border-width: 1px;border-style: solid;border-color: black;}"
$tableProperties = $tableProperties + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;}"
$tableProperties = $tableProperties + "TD{text-align:center;border-width: 1px;padding: 5px;border-style: solid;border-color: black;}"
$tableProperties = $tableProperties + "</style>"

# Main section of check
Write-Host "Looking for snapshots"
$date = get-date
$datefile = get-date -uformat '%m-%d-%Y-%H%M%S'
$filename = "F:\VMwareSnapshots_" + $datefile + ".htm"

#Get your list of VMs, look for snapshots. In larger environments, this may take some time as the Get-VM cmdlet is not very quick.
$ss = Get-vm | Get-Snapshot
Write-Host "   Complete" -ForegroundColor Green
Write-Host "Generating snapshot report"
$ss | Select-Object vm, name, description, powerstate | ConvertTo-HTML -head $tableProperties -body "<th><font style = `"color:#FFFFFF`"><big> Snapshots Report (the following VMs currently have snapshots on!)</big></font></th> <br></br> <style type=""text/css""> body{font: .8em ""Lucida Grande"", Tahoma, Arial, Helvetica, sans-serif;} ol{margin:0;padding: 0 1.5em;} table{color:#FFF;background:#C00;border-collapse:collapse;width:647px;border:5px solid #900;} thead{} thead th{padding:1em 1em .5em;border-bottom:1px dotted #FFF;font-size:120%;text-align:left;} thead tr{} td{padding:.5em 1em;} tbody tr.odd td{background:transparent url(tr_bg.png) repeat top left;} tfoot{} tfoot td{padding-bottom:1.5em;} tfoot tr{} * html tr.odd td{background:#C00;filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='tr_bg.png', sizingMethod='scale');} #middle{background-color:#900;} </style> <body BGCOLOR=""#333333""> <table border=""1"" cellpadding=""5""> <table> <tbody> </tbody> </table> </body>" | Out-File $filename
Write-Host "   Complete" -ForegroundColor Green
Write-Host "Your snapshot report has been saved to:" $filename

# Create mail message

$server = "yourmailserveraddress.com"
$port = 25
$to      = "youremailaddress"
$from    = "youremailaddress"
$subject = "vCenter Snapshot Report"

$message = New-Object system.net.mail.MailMessage $from, $to, $subject, $body

#Create SMTP client
$client = New-Object system.Net.Mail.SmtpClient $server, $port
# Credentials are necessary if the server requires the client # to authenticate before it will send e-mail on the client's behalf.
$client.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials

# Try to send the message

try {
    # Convert body to HTML
    $message.IsBodyHTML = $true
    $attachment = new-object Net.Mail.Attachment($filename)
    $message.attachments.add($attachment)
    # Send message
    $client.Send($message)
    "Message sent successfully"

}

# Catch an error

catch {

	"Exception caught in CreateTestMessage1(): "

}

 

Another point worth mentioning – you should change the path that the report is saved to on disk – in my script it is set to F:\, so just modify this to suit your environment. Kudos to Andrew at winception for his Snapshot checking code – I have used a lot of it above, but modified it somewhat to include additional information, and style the HTML table so that it is much easier on the eyes. I also added the e-mail functionality to the script. The following is a screenshot after I executed the script in PowerCLI manually. You would of course look to automate the process by scheduling this script in on your machine.

 

 

Enjoy, and please drop any comments, improvements or feedback in the comments section!