Adding a Percent Free Property to your Get-Datastore cmdlet results using Add-Member

 

Update:

 

Thanks to Alan Renouf  (@alanrenouf) for pointing out the New-VIProperty cmdlet to me, I was able to go back to the drawing board and really shorten up my original PowerCLI script by using the New-VIProperty cmdlet. @PowerCLI on twitter also pointed this out shortly afterwards. So after taking a quick look at the reference documentation for the cmdlet, here is my new VIProperty to get the “PercentFree” for each Datastore object returned from the Get-Datastore cmdlet!

 

New-VIProperty -Name PercentFree -ObjectType Datastore -Value {"{0:N2}" -f ($args[0].FreeSpaceMB/$args[0].CapacityMB*100)} -Force

 

To use it, simply run the above in your PowerCLI session, then use “Get-Datastore | Select Name,PercentFree”. A better option would be to load the above New-VIProperty script into your PowerCLI / PowerShell profile. Taking it one step further, @LucD has kindly offered to add this to his VIProperty Module, which means you could instead, just load this module in to your profile and benefit from all the other great VIProperty extensions! Example usage below:

 

New-VIProperty -Name PercentFree -ObjectType Datastore -Value {"{0:N2}" -f ($args[0].FreeSpaceMB/$args[0].CapacityMB*100)} -Force
Get-Datastore | Select Name,FreeSpaceMB,CapacityMB,PercentFree

 

You can find tons of other great VIProperties, or even download the entire module over at LucD’s blog.

 

Original Post:

 

I have been using the Get-Datastore cmdlet quite frequently at my workplace lately – mainly to gather information on various datastores which I export to CSV, then plug into Excel to perform further sorting and calculations on. To save myself a step in Excel each time (creating columns in spreadsheets to show and format the Percent Free figure of each Datastore), I decided to add this into my PowerCLI script.

 

Below, I’ll show you a fairly simple script that will add a member “NoteProperty” (A property with a static value) to your Datastore PS Objects. In the script, we’ll grab all the Datastores based on a search criteria (by default this will get all Datastores or Datastores with the word “Shared” in their name, but you can change it to match what you would like), then we’ll iterate through each, calculate the Percentage of free space from the two figures that we are given back already from Get-Datastore (CapacityMB and FreeSpaceMB), and finally add the member property to the current datastore object. Once this is done, we’ll output the results of  the $datastores object using “Select” to show the Name, Free Space in MB, Capacity in MB, and Percent Free of each object contained within to a CSV file (Remove the | Export-Csv part on the end if you just want the results output to console instead).

 

 

function CalcPercent {
	param(
	[parameter(Mandatory = $true)]
	[int]$InputNum1,
	[parameter(Mandatory = $true)]
	[int]$InputNum2)
	$InputNum1 / $InputNum2*100
}

$datastores = Get-Datastore | Sort Name
ForEach ($ds in $datastores)
{
	if (($ds.Name -match "Shared") -or ($ds.Name -match ""))
	{
		$PercentFree = CalcPercent $ds.FreeSpaceMB $ds.CapacityMB
		$PercentFree = "{0:N2}" -f $PercentFree
		$ds | Add-Member -type NoteProperty -name PercentFree -value $PercentFree
	}
}
$datastores | Select Name,FreeSpaceMB,CapacityMB,PercentFree | Export-Csv c:\testcsv.csv

 

Here’s an example of our output:

 

Note that you could simplify the script by removing the function called “CalcPercent” and adding it to your PowerShell or PowerCLI environment profile. Hope this helps!

 

How to create a PowerShell / PowerCLI profile & add Functions for later use

 

Ever wondered how to set yourself up a PowerShell or PowerCLI profile? Or how to go about saving useful Functions that you have created or picked up elsewhere to your profile for use in new sessions? Here I’ll detail the basics of PowerShell or PowerCLI session profiles and show you how to set one up, as well as how to save your first Function to this profile for use in future sessions.

 

Creating a PowerShell (or PowerCLI) profile is a great idea if you are considering spending any decent amount of time in the shell or executing scripts.  They allow you to customise your PowerShell / PowerCLI environment and apply useful functions or elements to every new PowerShell / PowerCLI session you start, without the need to reload these items yourself each time. A few examples of what you can add to your profile are functions, variables, cmdlets and snap-ins. This makes life so much easier when scripting or working on your latest bit of automation.

 

To begin with, you can see the currently set profile path in your session by typing $profile in the shell. If you would then like to edit your profile, try issuing the command “notepad $profile”. This will (if it exists) open your profile in notepad to edit. If it doesn’t exist, you’ll get an error when notepad tries to load indicating so. If this is the case, or you would like to create a new PowerShell profile for use in PowerShell or PowerCLI, use the last bit of script listed in the next section to create a profile and get started with customising your environment.

 

Show your profile path or open it up for editing in notepad:

$profile
notepad $profile

 

Create a new PowerShell profile for the current user if one does not already exist, then open it up for editing in notepad:

if (!(test-path $profile)) 
           {new-item -type file -path $profile -force}
notepad $profile

 

Once you have your profile created and ready for editing, try add a few useful Functions or variable declarations to get yourself going, then launch a new PowerShell or PowerCLI session to try them out. Here is a quick example of a function you can create to test your profile out in PowerCLI:

 

function VMInfo {
	param(
	[parameter(Mandatory = $true)]
    	[string[]]$VMName)
	Get-VM $VMName
}

 

Save your profile with the above function added, then start a new session of PowerCLI. Connect to your vCenter server using Connect-VIServer and then try type in “VMInfo aVMname” (where aVMname = the name of an actual VM in your environment). As you may have noticed, this function is just doing the same job that the Get-VM cmdlet already does for you, and will simply return the info about a VM specified. Here is a quick run down of the function above. The function is declared first of all (Name of the function). Then we open curly brackets to start the code. The param section then defines whether a parameter is mandatory (needed) or not, and what type of variable that parameter is (in our case we used a string), as well as giving the parameter a variable name ($VMName). The last bit does the actual work to run the Get-VM cmdlet on the parameter ($VMName) passed to the function. Here’s the output when running the new function against a VM called “SEAN-DC01” in my PowerCLI session:

 

 

You should now be able to see how useful this can become – you can quickly add new functions, variables, etc to your PowerShell profile for future use in new sessions. Try think of a few useful ones for cmdlets that you use often on a day to day basis and add these into your profile. You won’t regret it in the long run!

VMware Workstation 8.0 – Mini review and walkthrough of some features

 

I have up until now been using my VCP 4 copy of Workstation 7.0 for all my VM and vSphere Lab purposes. It has been great, and has allowed me to do a lot more testing / prototyping. Workstation 8.0 was recently released, so I decided to grab the evaluation version to play around with. My first impression: “Wow!” There are tons of new features available, as well as a nice newly redesigned UI. I’ll detail the features that mean the most to me to start with, and then walkthrough a very handy feature of VMware Workstation 8.0 – importing VMs from your local Workstation into a vCenter environment!

 

Virtualising Intel VT-x/EPT or AMD-V/RVI

First off, the main pull of Workstation 8 for me was the ability to virtualise Intel VT-x/EPT or AMD-V/RVI. When enabled, this passes through these special CPU feature sets into your VMs, which for ESXi / vSphere labs, means you can now run nested x64 virtual machines. Previously with Workstation 7.0 I was limited to only being able to power up 32 bit VMs in my virtualised vSphere lab environment. Enabling this option for virtualised ESXi 4.1 or 5.0 hosts now allows me to power up 64 bit VMs, which is great!

 

 

Connect Workstation to a vCenter or ESXi host

This is also a solid new feature. I was able to easily add my Virtualised vCenter server into Workstation (the platform that was running the VM anyway!) as a node. From there you open up other new features, such as…

 

Uploading VMs running in Workstation to vCenter

Awesome feature in my opinion. In the past I would have used something like VMware Converter to convert a Workstation VM into a vSphere compatible VM and then upload it to vCenter. Now it is a simple case of drag and drop, or a couple of menu clicks once you have added your vCenter server as a node in Workstation.

 

3D Acceleration and Surround audio features for VMs

This is something I have been waiting for from VMware, not the typical kind of thing I would usually look at for business purposes (unless I was doing CAD or 3D modelling), but I am an avid gamer, so this is of great interest to me. I’ll definitely be testing running a couple of my games inside a VM to try this out.
 

 

A quick walk through uploading VMs from Workstation to vCenter

 

Uploading a Virtual Machine running on your local machine running in Workstation 8.0 to your vCenter server or ESX / ESXi host is really simple – either a drag and drop affair, or you can right click the machine you need to move and choose to upload it somewhere else. Here’s a quick rundown on how to do this.

 

I’ll be adding my vCenter server to Workstation. Just click File -> Connect To Server and then specify the IP / name of your vCenter server. Specify some valid vCenter credentials and click OK. Here is my vCenter server added as a node:

 

 

Next up, we just simply right-click a VM running in Workstation 8, and choose Manage -> Upload

 

 

Select your vCenter server connection, specify a folder or location to place the VM, choose a shared Datastore to store the VM on, and then finish the wizard. Your VM should begin to upload to vCenter! If you hit any problems, check the permissions of the account you connected to vCenter with, as well as DNS – if your local workstation does not resolve the FQDN of your vCenter server or ESXi hosts correctly it will give you an error.

 

 

 

 

 

Out of interest, here is the spike in Write traffic to my lab’s iSCSI Datastore being used to house the imported VM whilst the upload was in progress.

 

 

So that is the quick walkthrough – nice and simple. You could save yourself a couple of clicks in the process above by simply dragging and dropping the VM too! Have you tried Workstation 8.0 out yet? What are you primarily using it for? I would also like to know whether VMware will be handing out version 8 licenses to candidates who pass their VCP 5 exams too. I’ll be taking my updating my VCP 4 to 5 soon and would love to have an upgrade to my Workstation 7.0 license!

 

vSphere 5 & HA Heartbeat Datastores

 

I was busy updating my vSphere lab from 4.1 to 5 and ran into a warning on the first ESXi host I updated to ESXi 5.0. It read: “The number of vSphere HA heartbeat datastores for this host is 1, which is less than required: 2”. The message itself is fairly self-explanatory, but prompted me to find out more about this as I immediately knew it must be related to new functionality.

 

The Configuration Issue message

 

Pre-vSphere 5.0, if a host failed, or was just isolated on its Management Network, HA would restart the VMs that were running on that host and bring them up elsewhere. (I have actually seen this happen in our ESX 4.0 environment before!) With vSphere 5.0, HA has been overhauled and I believe this new Datastore Heartbeat feature is part of making HA more intelligent and able to make better decisions in the case of the Master HA Host being isolated or split off from other hosts. This Datastore Heartbeat feature should help significantly in the case of HA initiated restarts, allowing HA to more accurately determine the difference between a failed host and a host that has just been split off from the others for example.

 

vCenter will automatically choose two Datastores to use for the Datastore Heartbeat functionality. You can see which have been selected, by clicking on your cluster in the vSphere client, then choosing “Cluster Status”. Select the “Heartbeat Datastores” tab to see which are being used.

 

Cluster Status - viewing the elected HA Heartbeat Datastores

 

Without going into too much detail, this mechanism works with file locks on the datastores elected for this purpose. HA is able to determine whether the host has failed or is just isolated or split on the network by looking at whether these files have been updated or not. After my lab upgrade I noticed a new folder on some of my datastores and wondered at first what these new files were doing there! If you take a look at the contents of the Datastores seen your Heartbeat Datastores tab, you should see these files that HA keeps a lock on for this functionality to work.

 

Files created on HA Heartbeat Datastores for the new functionality

 

So, if you notice this configuration issue message, chances are your ESXi 5 host in question simply doesn’t have enough Datastores – this is likely to be quite common in lab environments, as traditionally we don’t tend to add many (well at least I don’t!) In my case this was a test host to do the update from 4.1 to 5 on, and I only had one shared datastore added. After adding my other two datastores from my FreeNAS box and an HP iSCSI VSA, then selecting “Re-configure for HA” on my ESXi host, the message disappeared as expected. I believe there should be some advanced settings you could also add to change the number of datastores required for this feature, but I have not looked into these yet. Generally, it is also always best to stick with VMware defaults (or so I say) as they would have been thought out carefully by the engineers. Changing advanced settings is also usually not supported by VMware too. However, if you find you are short on Datastores to add and want to get rid of the error in your lab environment, then this shouldn’t be a problem to change.

PowerCLI – Get HA Restart Priority and Memory Overhead for VMs

 

Another day, another PowerCLI automation script. Here is a handy cmdlet that will fetch you a list of VMs in your environment based on whether they are currently powered on.

 

The interesting bit of info retrieved is their current HA Restart Priority. This will be returned whether the VM itself has its own HA Restart Priority defined, or if the VM is getting this setting from the cluster it is running in. Another interesting bit of info we fetch is the VMs current Memory Overhead figure. Additionally, we also fetch some other useful information such as which Host the VM runs on and the RAM & vCPU assignments for the VM, sorting the whole list by the name of each VM. Remember that the Memory Overhead that is reported back is what the current overhead for the VM is. This can change and there is quite a bit involved in how it is worked out. Further reading on Memory Overhead for VMs can be done here. Read Table 3-2 on page 30 of the linked PDF for the specifics.

 

(Get-VM | Where {$_.PowerState -eq "PoweredOn"}) | Select Name,PowerState,NumCpu,MemoryMB,VMHost,@{N="MemoryOverhead";E={$_.ExtensionData.Runtime.MemoryOverhead/1MB}}, HARestartPriority | Sort Name | ft

 

If you don’t want a result formatted in a table, just remove the “| ft” at the end of the cmdlet, and remember if you want to push the results of this into a CSV file, you can also just replace the “ft” with a “Export-CSV C:\yourfile.csv”. If you have any improvements to the above script, suggestions or comments, please add do add them!