Home > Blogs > VMware PowerCLI Blog > Monthly Archives: February 2012

Monthly Archives: February 2012

Using PowerCLI for Intra-VM Affinity rules in Storage DRS

Posted by
Alan Renouf
Technical Marketing

Recently Frank Denneman posted an excellent article on Storage DRS and particularly the impact of Intra-VM affinity rules on storage DRS, if you are using Storage DRS or thinking about implementing it or even just like to keep up with the latest vSphere 5 features I strongly suggest reading his article here.

You may have noticed some PowerCLI code on his post which explains how to disable the Intra-VM affinity rule for each Datastore Cluster, I wanted to expand on this a little, as Frank mentioned, there is currently no GUI setting for this feature so we need to rely on the CLIs to help change this.

Below you will find a number of examples on how to use a function called Set-DatastoreClusterDefaultIntraVmAffinity which was created to ease you in enabling and disabling this feature, with the below code we can also list each Datastore Cluster and see if this feature is indeed Enabled or Disabled currently.


In PowerCLI 5.0 we introduced a new Cmdlet called Get-DatastoreCluster, this can be used to list the Datastore Clusters which currently exist in your vSphere Environment, using this cmdlet we can easily add our hash-table which displays the current Intra-VM Affinity setting:

The code is listed below for you to be able to copy and paste:

Get-DatastoreCluster | Select Name, @{N="DefaultIntraVmAffinity";E={($_ | Get-View).PodStorageDRSEntry.StorageDRSConfig.PodConfig.DefaultIntraVmAffinity}}


Once listed we can use a PowerShell Advanced Function to disable or enable this setting, the function is listed below for you to copy and paste as needed:

function Set-DatastoreClusterDefaultIntraVmAffinity{
        [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]

        $SRMan = Get-View StorageResourceManager
        if($DSC.GetType().Name -eq "string"){
          $DSC = Get-DatastoreCluster -Name $DSC | Get-View
        elseif($DSC.GetType().Name -eq "DatastoreClusterImpl"){
          $DSC = Get-DatastoreCluster -Name $DSC.Name | Get-View
            $spec = New-Object VMware.Vim.StorageDrsConfigSpec
            $spec.podConfigSpec = New-Object VMware.Vim.StorageDrsPodConfigSpec
            $spec.podConfigSpec.DefaultIntraVmAffinity = $Enabled
            $SRMan.ConfigureStorageDrsForPod($DSC.MoRef, $spec, $true)

Once this function has been run we can easily use it to firstly disable the feature:


And also, if needed we can re-enable this feature by using the same function:


Hopefully this shows you that sometimes we don’t have to wait for features and settings to arrive in the GUI before we can use them, sometimes we can rely on the CLIs to help us out.

vSphere 5.0 Automation with PowerCLI

Posted by
Alan Renouf
Technical Marketing

At the end of last year, December the 9th 2011 to be exact, I was lucky enough to present at the Dutch VMUG with Luc Dekens who is known very well in the PowerCLI Community and for his excellent PowerCLI blog over at Lucd.Info

Our presentation was entitled “vSphere 5.0 Automation with PowerCLI” and was based on a presentation which was given by Raymond Epping and Jan-Willem Lammers, their presentation showed the top 10 features and enhancements which were introduced in vSphere 5.0.

Luc and I expanded on this by seeing which of these features we could automate in PowerCLI, the session was well received and we came up with some great scripts and functions which Luc and I have been sharing on our blogs over the past weeks. 

You can read more about the scripts and functions by following the links in the “Further reading and scripts” section of this post.


The full presentation is available from the Dutch VMUG site, check it out there are some great slides and scripts in there: http://www.vmug.nl/downloads/VMUG2011/vs5AutomationwithPowercli.pdf

How long do your vMotion/SvMotion take ?

One of the scripts I wanted to highlight was a handy advanced function we created called Get-MotionDuration.

Get-MotionDuration will look back through the events of your vCenter and recall your vMotion and SvMotion history, it will then present you with a list of these events and how long they took, an example of this output can be seen below.


Obviously the timings will change based on the size and how utilized the virtual machine is but this is great for comparing vSphere 4 systems against vSphere 5 where multiple enhancements have been made to the speed of vMotion and SvMotion giving you the benefit of quickly being able to put hosts into maintenance mode or move VMs to new datastores.

Watch it in action

The following video shows this script in action:


Get-MotionDuration Script

Function Get-MotionDuration {
    $events = Get-VIEvent -Start (Get-Date).AddDays(-1)
    $relocates = $events |
        where {$_.GetType().Name -eq "TaskEvent" -and $_.Info.DescriptionId -eq "VirtualMachine.migrate" -or $_.Info.DescriptionId -eq "VirtualMachine.relocate"}
    foreach($task in $relocates){
        $tEvents = $events | where {$_.ChainId -eq $task.ChainId} |
            Sort-Object -Property CreatedTime
            New-Object PSObject -Property @{
                Name = $tEvents[0].Vm.Name
                Type = &{if($tEvents[0].Host.Name -eq $tEvents[-1].Host.Name){"svMotion"}else{"vMotion"}}
                StartTime = $tEvents[0].CreatedTime
                EndTime = $tEvents[-1].CreatedTime
                Duration = New-TimeSpan -Start $tEvents[0].CreatedTime -End $tEvents[-1].CreatedTime

Connect-VIServer MyViServer –User Administrator –Password “Pa$$w0rd”

Get-MotionDuration | FT -AutoSize

Further reading and scripts

The following blog posts were created with examples from the Dutch VMUG presentation, please find time to check them out as they may save you time in the future….

Guest Post: Finding your way in the PowerCLI Community

Posted by
Luc Dekens
PowerCLI Community Member


The VMTN PowerCLI Community is a vast repository of PowerCLI scripts and snippets. At the time of writing this post, there were nearly 5000 threads and more than 80 documents posted.

With so many threads present, it happens quite often that users ask a question that was already answered in a different thread. The problem is that most users of the PowerCLI Community don’t really know how to search the threads and documents. Admittedly, the search functionality offered in the VMTN communities is not the easiest and most intuitive one to use. Hence this post that should give you a couple of pointers on how to use the PowerCLI Community as (very) big repository of PowerCLI goodies.

Starting a search

On any page of the community you will see a search box near the top right corner of your browser page.


Let’s type some text, for example ‘svmotion’ in the search field. The forum software will now automatically open a drop-down box with some first results.


You have 3 options to continue.

1. By clicking the magnifying glass or the ‘View All Results’ text, the Search page will open. From there you can select one of the displayed threads or documents, or you can further refine your search.

2. The results that are displayed in the drop-down box do not come from the PowerCLI Community alone. They are entries found throughout all the Communities in the VMTN forum. By clicking on the ‘Only for VMware vSphere ™ PowerCLI’ hyperlink at the top of the drop-down box, the contents of the drop-down box will change. It will contain only entries coming from the PowerCLI Community.


If you now click on the ‘View All Results’ hyperlink, you will be taken to the Search page, similar to the first option. But the Search page will only contain entries from the PowerCLI Community.

Note that clicking the magnifying glass you will be taken to the Search page, but the results will come from all VMTN communities!

You can go back to the results from all the VMTN communities by clicking the ‘All’ hyperlink at the top of the drop-down box.

3. If you see in the list a post whose title suggests that it might contain what you are looking for, you can click on that line. The selected thread will open.

The Search page

This is the page where you have a plethora of options at your disposal to refine your search.


1.  Add words to refine your selection criteria.

On the ‘Search Tips’ you can find many ways to fine-tune your search. A short extract of the more important search rules:

  • When you enter multiple words, the search will look for threads and documents that contain all of the words.
  • When 1 or both of the words should appear in the thread or document, use OR between the words. For example: ‘svmotion OR vmotion
  • Put the logical operators in Caps to distinguish them from your search keywords.
  • When looking for an exact sequence of words, place them in double quotes. For example: ‘”background job”
  • Use the fuzzy search (~) when you are not 100% sure of the word(s) you’re looking for. For example: ‘motion~’’
  • Use a weight (^n) on specific words to make them more important in your search. For example: ‘svmotion^2 vmx’. This will make the presence of ‘svmotion’ twice as important as the presence of ‘vmx’.
  • Indicate in which part of the post (subject, body, tags or attachmentsText) you want to search for a word. For example: ‘subject:svmotion
  • Specify words that should not be in the results. For example: ‘svmotion NOT vmx
  • Use parenthesis to create complex search strings. For example: ‘svmotion AND (vmdk OR vmx)

2.  Under ‘More options’ you can limit your search to a specific Community or a specific person. When you want to select a specific Community, type part of the Community name and select one of the Communities that is proposed.


Note that you will have to start with ‘vsphere’ to get to the PowerCLI Community !


The search will now be limited to the PowerCLI Community.

3. When the search returns a number of hits, you can order the results by Date, Subject or Relevance.


The options Subject and Date are self-explanatory. The Relevance option is a percentage given by the Jive search algorithm to the search results, indicating how much a specific search result corresponds with the search query.

The best results, according to the search algorithm, will appear at the top of the list.

4. With the ‘What’ options you can filter the results based on where they are found. In the PowerCLI Community the only usable options are All, Discussions or Documents. The Blog Posts and Links do not seem to be used in the PowerCLI Community.

The options correspond with the Tabs you see on the PowerCLI Community page.


5. The ‘When’ option allows you to specify in which period in the time you want to search. You can select Anytime, the past Day, Week, Month or Year.

Since the oldest threads in the PowerCLI Community date from December 2007, this can be a handy option to limit the search results to those that correspond with the actual PowerCLI version.

Remember that there are on average 2 new PowerCLI versions per year, and that each of these brings a bunch of new Cmdlets and sometimes even complete snapins. So a valid answer from 2008 is not necessarily the best answer for the latest PowerCLI version !

Some practical examples

With the knowledge from the previous section, you should now be able to perform very precise searches and get useful results. Since I’m a strong believer in the “learn by example” principle, I added a couple of practical examples in this section that will hopefully help you getting started.

Know the defaults of the Search

Remember that the Search engine by default will use AND if you enter multiple keywords.

Use OR when you want results that contain one or the other of the keywords to be present in the results.

Instead of doing ‘vmx tools copy paste’ use ‘vmx AND tools OR copy OR paste’.

Don’t use only general keywords

Try to avoid using general search terms that will produce hundreds of results.

Don’t search for ‘PowerCLI vm report’, instead use one or more specific keywords ‘vm report numcpu’. In this example the addition of the numcpu keyword will get you more specific results.

Try to use very specific keywords

This is perhaps a stupid advice, but one that could save you a lot of time.

Suppose you are looking for a thread that discusses deploying a VM from a template and that includes information on customizing the NIC of the guest.

Your first thought could be to type ‘deploy vm template nic customise’, this returned 27 threads.

If you know that you can use the Set-OSCustomizationNicMapping cmdlet for this, add the cmdlet in the keywords. That returned only 1 thread.

Use the VMware vSphere PowerCLI Overview

In the previous example the addition of the Set-OSCustomizationNicMapping keyword to the search, gave us a better search result. But how do you know that cmdlet exists if you are new to PowerCLI or had never used the cmdlet before.

In the VMware vSphere PowerCLI Overview you can use the search functionality to help you discover the Cmdlets. In this example when you for example type the word ‘nic’, the reference will return a number Cmdlets, including the Set-OSCustomizationNicMapping cmdlet.


Note that you also search for Types, Parameters and Enumerations.

Use the More and Filter Options

Do not only use keywords. Sometimes it is useful to add 1 of the More options to fine-tune your search.

For example, searching for ‘vcheck’ (the famous reporting script) will return 34 results. By adding the name of the user who posted or replied, you can limit the number of results. The same query, but with the addition of the Restrict to a specific person option, will return only 3 results.


If you want to find results that are more likely to discuss the most recent version of the vCheck script, use the When option.


This produced 3 results that all referenced vCheck v6.

Let Bookmarks help you

I don’t know if this already happened to you, but I often find a useful or interesting thread that I can’t find back after a couple of days. To avoid this use the Bookmark feature to add such a thread to your list of threads that you want to keep for later consultation.

You can find the Bookmark option on the right side under the Actions,


click it and optionally enter some notes to go with the bookmark. Note that you make your bookmarks public or private.


You can consult your Bookmarks through the My Bookmarks entry in your user accounts drop-down menu.


PowerCLI first steps with LucD

Many of you have probably had a communities post answered by LucD… I know I have!

He it the most active PowerCLI member and one of the most respected vExperts and PowerShell/PowerCLI users in the community.  Luc has presented at many VMworld sessions and VMUGS alike, he has a great blog with some great posts here: Lucd.info

For those of you wanting to learn PowerCLI and not knowing where to start idera recently announced he will be performing a session on PowerCLI first steps.

This is highly recommended for both beginners and experts alike.


Wednesday, March 28, 2012

12:00 – 01:00 PM Central Time

Register here: https://www.vconferenceonline.com/event/regeventweb.aspx?id=560

PowerCLI at Partner Exchange

Alan Renouf – Sr. Technical Marketing Architect

With Partner Exchange (PEX) just around the corner from Feb 11th to Feb 16th I wanted to share the PowerCLI sessions with you, there are a couple of great sessions related to PowerCLI this year as you can see from the below information.

As well as these sessions I will also be walking the floors of the Solutions Exchange chatting to the cloud providers and anyone who has anything to do with Automation or just looking to make their lives easier.

I will also be keen to talk to anyone who is thinking of creating a cloud or has a cloud at the moment using vCD, I have some cool things to show you which will help you streamline your vCD environment – Reach out to me !

(TEX1481) vCloud Infrastructure Automation – powered by PowerCLI

Speakers: Vladimir Goranov and Alan Renouf

Date/Time: 02/14/2012 2:45 PM -3:45 PM
Room: Murano 3203


Within an hour we’ll equip you with the ultimate weapon for reporting and automating vCloud Infrastructure.

Here are the ammunitions we have in the charger!

  • Get familiar with the available PowerCLI cmdlets used for reporting vCloud Infrastructure
  • Simple techniques to combine few cmdlets into a powerful report
  • Special equipment for scripting automation in cloudy weather

Become the first to plan your vCloud automation with all new capabilities of PowerCLI for vCloud Infrastructure – roadmap review You don’t have to live in the office to be an outstanding service provider.

(1548) Make customer's business fly with PowerCLI

Speaker: Laurynas Kavaliauskas

Date/Time: 02/16/2012 12:45 PM -1:45 PM
Room: Murano 3201A


Everyone talks about automation, but what do we really want to automate? What are the tools and APIs you can leverage with VMware's latest products? We will be walking you thru PowerCLI and automation use cases. We will show how simple script can accomplish in 1 minute what a team of 10 engineers can barely do in a week.

PowerCLI 5.0.1 vCloud Director – Stopping and starting vApps

In a previous video we showed you how to get started with PowerCLI 5.0.1 and specifically the vCloud Director (vCD) cmdlets, we show you how to gain a list of cmdlets which were added to PowerCLI 5.0.1 for managing vCD and how to use some of these cmdlets to gather data from your vCD infrastructure.

I received some comments from people saying this was great information and they could use this to write some scripts which would allow them to pull data from the vCD infrastructure, but how could they interact with vCD ?  At the moment the web interface gives them access to not only view the cloud data but also interact with it, stop/start vApp’s and VM’s, create new Organization’s, ProvidervDC’s, OrgvDC’s and much much more.

You may not know but this functionality is actually available in the PowerCLI 5.0.1 cmdlets.  When listing the cmdlets you will see that most start with “Get-“ which means they are mainly designed to retrieve the data.  People who have looked a little further or perhaps have slightly more PowerCLI knowledge will have noticed the cmdlet Get-CIView.

The Get-CIView cmdlet allows us to reach into the full SDK for vCloud Director and pull back the full .Net object, this basically means that we get access to perform anything in vCloud Director that you would normally do via the web interface.

Another way to retrieve the .Net View representation  of a PowerCLI object is to refer to its .ExtensionData property.

The .ExtensionData property is an “on-demand” property which gives us the same results as calling the Get-CIView cmdlet.

To see a simple example of how we might use this .Extensiondata property to interact with vCD and Start/Stop a vApp take a look at the below video example:

From this simple example we can then create PowerShell advanced functions to make this easier for us in the future as can be seen below, this will give us 2 functions which will allow us to easily stop and start vApps in the cloud using PowerCLI.

function Stop-CIVApp {
            Powers Off a vApp.

            Powers Off a vApp and all VMs within it.

        .PARAMETER  CIVApp
            The Name or object or collection of objects of vApps which to shutdown.
        .PARAMETER    Force
            Attempt to power off the VMs. Failures in undeploying the VM or associated networks are ignored.
            All references to the vApp and its VMs are removed from the database

            PS C:\> Get-CIVApp | Stop-CIVApp

            PS C:\> Get-CIVApp “MyvApp” | Stop-CIVApp
            PS C:\> Stop-CIVApp -CIVApp “MyvApp”
            PS C:\> Stop-CIVApp -CIVApp “MyvAPP” -Force
    Process {
        if ($pscmdlet.ShouldProcess($CIVAPP)) {
            If ($Force){
                $CIVApp | Foreach {
            } Else {
                $CIVApp | Foreach {

function Start-CIVApp {
            Powers On a vApp.

            Powers On a vApp and all VMs within it.

        .PARAMETER  CIVApp
            The Name or object or collection of objects of vApps which to start.

            PS C:\> Get-CIVApp | Start-CIVApp

            PS C:\> Get-CIVApp “MyvApp” | Start-CIVApp
            PS C:\> Start-CIVApp -CIVApp
    Process {
        $CIVApp | Foreach {

Checking the Pay-As-You-Go MHz Issue

Whilst sitting in a vCD Deep Dive presentation by Aidan Dalgliesh and David Hill last week at the London VMUG they explained an issue which has been reported on multiple occasions, they have seen this more than once on customer deployments and the issue had been reported on the internet both by Massimo Re Ferre and Kendrick Coleman.

When setting up a new Organization vDC with a Pay-As-You-Go model the default vCPU Speed is set to 0.26 GHz, most people continue on through the wizard without changing this and end up crippling their VMs as this adds a CPU limit onto the VM meaning the VM will never get past this speed limit.


This of course gives us a great reason to produce a one-liner from the PowerCLI vCD snapin to check your complete cloud infrastructure for any Organization vDCs which may have this default still enabled.

Get-OrgVdc | Where {$_.AllocationModel -eq "PayAsYouGo"} | Where {$_.ExtensionData.VCpuInMhz -eq 260}

As you can see, the above one-liner firstly grabs all Organization vDCs and then checks these to see if their allocation model is “PayAsYouGo”, once it has found these it will check the vCPUInMHZ property to see if it is set to 260 or 0.26GHz.

An example of this can be seen below: