Home > Blogs > VMware PowerCLI Blog > Author Archives: Alan Renouf
Alan Renouf

About Alan Renouf

Alan Renouf is a Senior Technical Marketing Architect at VMware focused on the automation and integration of VMware products. Alan is a frequent blogger at http://blogs.vmware.com/vipowershell and has a personal blog at http://virtu-al.net. You can follow Alan on twitter as @alanrenouf.

Vote PowerCLI at VMworld 2013

imageIts time to vote for VMworld sessions again and this year there are a whopping 13 PowerCLI related sessions in the public voting for you to select, that’s a lot more than last year.

There is a good variety of sessions from learning up to the expert, from VMware engineers (The guys who wrote PowerCLI) and also customers who use PowerCLI.

Personally I would like to accept all of them but hey, its down to you so go to the VMworld Voting Page sign in and vote for your top sessions.

I’m looking forward to automation and fun filled VMworld this year!

4887 The PowerCLI – vSphere API Rosetta Stone
Josh Atwell
Conrad Ramos
Occasionally tasks that are simple in the vSphere GUI are not available as part of the native PowerCLI cmdlets. Automating these tasks require digging deeper into vSphere’s API, which is foreign to most PowerCLI scripters. PowerCLI can directly communicate with this API if you know the right places to look.Attendees will learn how to navigate the vSphere API to identify the methods required to perform these tasks. Additionally attendees will learn the basics on how to integrate these mysterious methods into PowerCLI through proven examples. We’ll help you learn the language of the vSphere API and translate it into powerful scripts and functions.
4910 Racking up Oracle RAC with PowerCLI
Maish Saidel-Keesing Have you ever set up Oracle RAC? Have you ever counted how many steps it takes to perform the full installation? How many of those have to be performed manually?Wouldn’t it be great to set up your Oracle RAC cluster with a minimal amount of steps and let the rest all be handled automatically?This Session will supply the use case of how our company managed to automate the full installation of Oracle RAC. Converting a manual, highly error prone and frustrating process, to something that is now 100% automated, and has reduced to the time to deploy a fully functional RAC cluster from 12-16 hours of manual work to a 60-90 minute automated process.The session will go through the workflow needed to complete a RAC installation – and will show you how we leveraged some our built-in processes and the vSphere API to complete the rest of the work.

The session will include a live demo of a full RAC installation from start to finish.

4944 PowerCLI Best Practices – A Deep Dive
Luc Dekens
Alan Renouf
In previous years Alan and Luc showed you some of their best practices and how to take PowerCLI one step further.
This year they will dive deeper and show you some best practices you didn’t see coming.
- The Software Defined Datacenter
- Taking on the MOB and winning
- From vSwitch to vDS
- Pimp your performance graphs
- Common and Cool Community Questions
4983 PowerCLI for dummies
Noam Perimann In this customer case study, an IT generalist shares real-world PowerCLI scripting solutions to monitoring and maintenance challenges in a Windows environment. Integrating vm-level and guest-level scripting, holistic automation is presented in digestible pieces. Even a dummy can become a productive automator.
5019 Automating Horizon View Administration with PowerCLI and LDAP
Jack McMichael As large Horizon View deployments scale up, so does the administration tasks that accompany it. Ease the pain of administration tasks, pool deployment, user entitlement, and desktop image management with the use of PowerCLI and the Horizon View ADLDS instance.In this advanced technical session we’ll setup our Connection Broker for use with PowerCLI. We’ll examine the most commonly used PowerCLI cmdlets and put them to use in real world examples that will help you streamline administration or create automated tasks to better manage a Horizon View environment. We’ll navigate into the Horizon View ADLDS instance to understand the information available, make you comfortable manipulating data when necessary, and show how you can integrate LDAP queries into scripts to aggregate the information you need that Horizon View Administrator may not show you.
5166 How to manage and automate large scale Cloud deployments through PowerShell / PowerCLI
Sajal Debnath The overall aim of this session is to enable cloud admins to effectively utilize PowerShell / PowerCLI in their day to day tasks to make it easier for them to manage the complex environments.The session starts with a discussion on common needs for automation in cloud environment, different methods of achieving same and their respective merits and demerits. It will then go on to discuss available PowerShell / PowerCLI way of automating and managing cloud environment. Different categories of cmdlets available under PowerCLI for vCloud environment and their uses and applications.Next it takes sample use cases and solve those using PowerShell scripts, describing in detail about the working of the scripts so that general idea can be gained about the requirements and how to approach to provide solutions to meet the requirements.In this stepwise approach has been taken where it starts from simple scripts and then gradually goes to more complex scripts.
5287 Open up the vCloud hood using PowerCLI, Hyperic, vCenter Operations Manager and vCenter Orchestrator to reveal the inner cloud.
Phil Ditzel
Cathal Cleary
Are you a vCloud service provider? Are you a vCloud consumer? Do you have enough visibility of what’s happening under vCloud Director’s hood?This session will discuss tools and techniques for both the provider and consumer to open up the vCloud box and allow for higher levels of utilization. We will demonstrate techniques using PowerCLI, vFabric Hyperic, vCenter Operations Manager and vCenter Orchestrator to add both provider and consumer instrumentation to vCloud Director.
5298 PowerCLI – from Youngling to Master
Hans De Leenheer Learning a new technology is like learning a new language. It is especially so if you want to learn a scripting language. At the VMware Community Podcast of March 27th, where the topic was PowerCLI, a question got raised where you should start when you are a rookie. The answer was “many places”. As a result of that PowerCLIforDummies.com got created that would be just that landing place to start.Making it interesting the website evolves through the stages of learning a new language. To keep it geek enough the learning process has been aligned with the Jedi ranks. By the end of this session you will know how to grow from Youngling to Apprentice, Knight and in the end become a real PowerCLI Master.
5338 What’s in PowerCLI for me?
Andrey Anastasov
Vladimir Goranov
Have you ever felt like you are doing the same thing over and over again? Are you tired of clicking with the mouse through tedious user interfaces and endless wizards? Are you having trouble keeping up with the loads of work around your virtual infrastructure?Then you might use some help – and PowerCLI is the tool for you! It lets you automate all aspects of your work: reporting, provisioning, and large-scale changes, to name a few. PowerCLI is powerful, yet easy to use.
5340 What everybody ought to know about reporting in the software-defined data center with PowerCLI
Andrey Anastasov
Vladimir Goranov
Administrators: Do you know what is going on in your virtual environment? Are you aware of the current trends in its usage? Are you in control of your software-defined infrastructure?PowerCLI will help you report on all aspects of your virtual environment and cloud infrastructure. Learn how to write simple yet powerful PowerCLI reports in various formats. Discover the five PowerCLI reports no vSphere administrator can live without and the amazing reporting capabilities PowerCLI provides for the software-defined data center.
5479 To the Cloud, with PowerCLI!
Jake Robinson
Alan Renouf
PowerCLI has become one of the most powerful and easy to use tools in a vSphere admin’s arsenal. Since version 5.01 this also includes the ability to manage your workloads in the public cloud. This session will show you the power you have to manage workloads at any vCloud provider, see how easy it is to create, manage and report on your cloud workloads with PowerCLI
5554 How to use the new PowerCLI VMware vSphere Distributed Switch cmdlets and become a PowerCLI superstar
Robert van den Nieuwendijk While the VMware vSphere Distributed Switch has been around since vSphere 4, official vSphere PowerCLI support for the VMware vSphere Distributed Switch was just recently introduced in VMware vSphere PowerCLI 5.1 Release 2. This session will provide a technical deep dive into the new PowerCLI cmdlets to manage a vSphere Distributed Switch. You will learn how to configure and manage a vSphere Distributed Switch using PowerCLI. Exporting and importing the configuration of a vSphere Distributed switch will be discussed in depth. You will learn how to import the configuration of a vSphere Distributed switch to create new distributed switches and port groups, or to modify existing ones. Finally migrating a standard vSwitch to a vSphere Distributed Switch will be highlighted.
5731 Become a Rock Star with PowerCLI and vCenter Orchestrator – Now with more Cowbell
Josh Atwell Automation is the future of cloud and in this session attendees will learn how to identify areas in their environment that are primed for less administrator interaction. The combination of PowerCLI and vCenter Orchestrator puts considerable power in even the greenest users. Attendees will learn how to identify areas for automation and start learning to discern which tool is best suited for the job and when to use them together.

Joining ESXi hosts to a domain and granting permissions with PowerCLI

Recently I was asked by an administrator to help him automate the process of joining ESXi Hosts or as PowerCLI refers to them “VMhosts” to a domain and granting permissions for a domain user with PowerCLI.

In this post I am going to show you how this can be done with a few lines of code and also share my lessons learned throughout this process. Let’s assume that you have list of VMhost IP addresses and all VMhosts have the same local administrator credentials, you want to join them to a domain and grant permissions for a domain user or group account assigning it a specific role. In the script I assume the role exists on the VMHost but later I will show you how to create a custom role.

The Set-VMHostAuthentication cmdlet is used for joining a VMhost to a domain. You should have in mind that the full domain name must be specified on the Domain parameter of the cmdlet.

Get-VMHostAuthentication -VMHost <VMHost>| Set-VMHostAuthentication -Domain <domain fullname> -User <domain user name for authentication> -Password <password for authentication> -JoinDomain -Confirm:$false

The New-VIPermssion cmdlet is used for creating permissions for a specified user. The user is obtained with the Get-VIAccount cmdlet which has the ability to retrieve Domain user or group accounts when the VMHost is joined to a domain. In contrast to Set-VMHostAuthentication the Domain parameter of Get-VIAccount expects the domain alias instead of domain full name.

You should also be aware that if you don’t specify an Id filter to the Get-VIAccount cmdlet it returns the maximum 5000 results and for domains with many accounts this could be a constraint. So it is recommended to use Id filter of the cmdlet itself instead of applying filtering over its results.

To obtain domain user accounts use –User switch.

Get-VIAccount -Domain <domain alias> -User -Id <user name filter>

To obtain domain group accounts use –Group switch.

Get-VIAccount -Domain <domain alias> -Group -Id <group name filter>

To grant permissions you should specify account to Principal parameter returned by the Get-VIAccount cmdlet, role which can be obtained by Get-VIRole or specified by name and entity which in our case will be the VM host.

New-VIPermission -Principal <VIAccount> -Role <VIRole> -Entity <VMHost>

Here is the entire script with a lot of input parameters needed by the used cmdlets in the script but the script itself is not complex:

param (

   [Parameter(Mandatory=$true, HelpMessage="List of VM host IPs")]

   [ValidateNotNull()]

   [string[]]

   $vmHostIPs,

 

   [Parameter(Mandatory=$true, HelpMessage="VM Host User Name")]

   [ValidateNotNull()]

   [string]

   $vmHostUserName,

 

   [Parameter(Mandatory=$true, HelpMessage="VM Host Password")]

   [ValidateNotNull()]

   [string]

   $vmHostPassword,

 

   [Parameter(Mandatory=$true,HelpMessage="Domain full name, required for joining hosts.")]

   [ValidateNotNull()]

   [string]

   $domainlFullName,

  

   [Parameter(Mandatory=$true,HelpMessage="Domain alias, required for retrieving domain accounts.")]

   [ValidateNotNull()]

   [string]

   $domainAlias,

 

   [Parameter(Mandatory=$true, HelpMessage="User name for domain authentication")]

   [ValidateNotNull()]

   [string]

   $domainUser,

 

   [Parameter(Mandatory=$true, HelpMessage="Password for domain authentication")]

   [ValidateNotNull()]

   [string]

   $domainPassword,

  

   [Parameter(Mandatory=$true, HelpMessage="Domain user name for which permissions will be granted")]

   [ValidateNotNull()]

   [string]

   $userNameToGrantPermissions,

  

   [Parameter(Mandatory=$true, HelpMessage="The name of the role you will assign to the user")]

   [ValidateNotNull()]

   [string]

   $roleName

)

 

 

foreach ($vmHostIPin$vmHostIPs) {

    # Establish connection to a VMHost

    $vmHostConnection= Connect-VIServer-Server $vmHostIP -User $vmHostUserName -Password $vmHostPassword

      try {

            # Get VMHost instance

            $vmHost= Get-VMHost -Server $vmHostConnection

     

            # Join the VMHost to a domain

            Get-VMHostAuthentication -VMHost $vmHost | Set-VMHostAuthentication -Domain $domainlFullName -User $domainUser -Password $domainPassword -JoinDomain -Confirm:$false

 

            # Get a domain account

            $viAccount= Get-VIAccount -Domain $domainAlias -User -Id $userNameToGrantPermissions        

            if (-not $viAccount) {

                  throw “VIAccount with Id ‘$userNameToGrantPermissions’ not found in domain ‘$domainAlias’”

            }

 

            # Get role to assign

            $viRole= Get-VIRole -Name $roleName

            if (-not $viRole) {

                  throw “VIRole with name ‘ $viRole’ not found.”

            }

 

            # Add permissions on VMHost

            New-VIPermission -Principal $viAccount -Role $viRole -Entity $vmHost         

      } catch {

            Write-Error (“The following error has occurred for VMHost ‘$vmHost’: `r`n”+$_)

      } finally {

            Disconnect-VIServer $vmHostConnection -Confirm:$false

      }

}

 

As you can see the script opens a connection to each VMhost, joins it to the domain and creates permissions for a specific domain account. It relies on the existing role on the VMHost, but it can be easily modified to create a custom role and assign it to the obtained user.

To create a new custom role the New-VIRole cmdlet needs to be used specifying a name and list of privileges on its input. Here is an example:

New-VIRole -Name MyCustomRole -Privilege ‘Anonymous’, ‘View’, ‘Read’, ‘Power On’, ‘Power Off’

The script is calling the Get-VIAccount with a –User switch parameter which filters on domain user accounts. In order to retrieve a domain group account the –Group switch parameter should be used.

So the script looks pretty simple and straightforward but running it I’ve experienced the following problem. Sometimes Get-VIAccount failed to retrieve the domain user immediately after joining the VMhost to the domain and I received the following error “Error accessing directory: Can’t bind to LDAP server for domain: <DOMAIN>”.

It seems that synchronization with active directory needs some time after a host is joined to the domain and the problem is not 100% reproducible. So I solved it with a simple retry-wait mechanism on retrieving domain users.

# Get a domain account

$viAccount=$null

$retryCount= 5

while ((-not$viAccount) -and ($retryCount-ge 0)) {

      try {

            $viAccount= Get-VIAccount-Domain$domainAlias-User-Id$userNameToGrantPermissions

      } catch {

            Write-Error “Getting VIAccount with Id ‘$userNameToGrantPermissions’ failed with the following error: `r`n $_”

            Write-Host “Next attempt in 5 seconds”

            Start-Sleep -Seconds 5

}

$retryCount

}

Conclusion

In conclusion here are the lessons learned from this task:

  1. Get-VIAccount requires to specify the domain alias to Domain parameter
  2. Get-VIAccount limits the results to 5000
  3. Sometimes Get-VIAccount fails to obtain domain users immediately after a VMhost is joined to a domain.

imageThis post was created by Dimitar Milov…

Dimitar joined VMware and PowerCLI team in the beginning of 2011. He is member of the quality engineering part of the team and his main role is the functional verification of the vSphere, vCloud and License PowerCLI components.

As all members of the team he is working to deliver a good and valuable product. He is also working to improve all processes and tools involved in product development and validation.

VDS Export/Import with PowerCLI

One of the great new features introduced in vSphere 5.1 was the ability to export and import the configuration of your vSphere Distributed Switch (VDS) and port groups to a file.

This gives you a quick restore method in case of issues or misconfigurations and also allows you to copy the entire VDS or port group configuration to a new VDS.  This feature is detailed by this VMware KB and is available via the vSphere Web Client, below you can see how we would do this via the web client:

image

Exporting the configuration with PowerCLI

With the introduction of the VDS cmdlets in PowerCLI 5.1 R2 we can also automate this process using the Export-VDSwitch and

Continue reading

PowerCLI Lab Online – Sign up now for the public beta

If you were at VMworld in 2012 you may have attended the Hands on Labs (HOL), this is normally one of the most popular areas at VMworld as it’s a time when people can use the applications they don’t currently have installed in their own environments, they can use a virtual environment to follow instructions and see how the applications really work.

One of the most popular labs at VMworld is always the PowerCLI Lab, this was no exception in 2012, every year the PowerCLI team does a great job of adding new features to the latest version of PowerCLI and this is always a great way to check those features out in a test environment.

There has always been one issue with the HOL though, once you leave VMware you say goodbye to the HOL as access was previously at the event only….. Until Now.

There is now a public beta of the HOL Online, this gives you access to a number of different HOL Online for you to take at your own leisure and sat at the comfort of your own desk.

How do I sign up?

To sign up simply go to http://hol.vmware.com and click on the link as highlighted below:

image

Once you have filled out a few questions you will need to wait for your account to be activated (I have been assured this will be fairly quick).  Once activated you will be able to click on the “VMware Hands-on Labs Online” link as above and access a number of different labs, complete with their own isolated environment and full step by step documentation to run through the lab chosen.

How do I find the PowerCLI Lab?

Once you have gained access to the HOL and signed in use the left hand menu to select “Cloud Infrastructure”

image

Now scroll down the list on the right until you see the PowerCLI Lab, then click Enroll.

image

Once you have done this the selected Lab will be added to “My Enrollments” where you will be able to click the “Start this LAB” button to launch the lab as below:

image

The LAB will now start and you will have access as seen below:

image

PowerScripting Podcast–What’s new in PowerCLI 5.1 R2

If you enjoy podcasts or have a long commute and don’t mind listening to people talk about PowerShell then I can highly recommend the PowerScripting Podcast, they have some great PowerShell information every week and if you have not listened before then you already have 219 podcasts to catch up on!

Recently I had the pleasure of being interviewed on the PowerScripting Podcast by Hal and Jonathan, we talked about what was new with PowerCLI, what was cool in the world of PowerShell and also what I would do on a trip to Mars (I know – Random!).

For more information and ways to download the podcast visit their site here: http://powerscripting.wordpress.com/2013/03/13/episode-219-alan-renouf-from-vmware-on-powercli/

For more information on what’s new in PowerCLI 5.1 R2 make sure you check out this blog post: http://blogs.vmware.com/vipowershell/2013/02/powercli-5-1-release-2-now-available.html

Retrieving vCloud Director VM Hard Disk size

I was asked recently if we were able to retrieve the disk space of a VM in vCloud Director through PowerCLI, on checking this I found that it is not currently part of the CIVM object and also there is currently no Get-HardDisk cmdlet equivalent like in the vSphere snapin.

After looking through the REST API Reference Documentation –> User Operations I found an entry for the VM VirtualHardwareSection  and specifically the disks which can be found as can be seen here: GET /vApp/{id}/virtualHardwareSection/disks

The virtualhardwaresection is easily accessed via PowerCLI using the extensiondata property which allows access to the back end API, I could then find my disk properties by filtering on the description of Hard Disk as in the example below:

(Get-VM MyCloudVM).ExtensionData.getvirtualhardwaresection().Item | Where { $_.Description -like “Hard Disk”}

Now I had the hard disk I noticed that part of the information was the capacity as highlighted below:image

With this information I could then find the capacity of the disk and add the information I needed into more of a friendly PowerShell property to the Hard Disk object.

So tying this all back together we could easily use the .ExtensionData reference to create our own Advanced PowerShell function to return the hard disk information for any CIVM.

Example

The following shows an example of how to use this new function and the output, this of course can also be used to export into CSV/HTML/Text or any other format PowerShell can be used with, it is also great for reporting on where the disk space in your cloud is being used!

image

The Code

Function Get-CIVMHardDisk {
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
$CIVM
)
Process {
$AllHDD = $CIVM.ExtensionData.getvirtualhardwaresection().Item | Where { $_.Description -like “Hard Disk”}
$HDInfo = @()
Foreach ($HD in $AllHDD) {
$HD | Add-Member -MemberType NoteProperty -Name “Capacity” -Value $HD.HostResource[0].AnyAttr[0].”#text”
$HD | Add-Member -MemberType NoteProperty -Name “VMName” -Value $CIVM.Name
$HDInfo += $HD
}
$HDInfo
}

}

Back to Basics: Connecting to vCenter or a vSphere Host

Following my previous post which took you through the install of PowerCLI I thought it was time to add another back to basics (B2B) post and show how to take the first step in using PowerCLI… Connecting to your vCenter or vSphere host.

Yes, PowerCLI can be used to connect to both vCenter and also the vSphere host independently, of course not all the cmdlets will be relevant if you connect to just the host but still, this can be useful during the initial setup or automated deployments of the complete infrastructure.

How to connect

If you are connecting to either a vCenter server or a vSphere Host the cmdlet is the same, you can use the Connect-VIServer cmdlet to connect to both of these (even at the same time), lets take a look at an example:

C:\PS>Connect-VIServer -Server vcenter01 -User admin -Password pass

In the above example you can see we are connecting to our vCenter server called “vcenter01” with a username and password to gain access to the vCenter server, we did not specify a protocol or port, by default HTTPS and port 443 is assumed which is the same as the vSphere Client or Web Client, unless you specify a –port or –protocol parameter for the cmdlet.

Credentials

In the example above we used the –User and –Password parameters to pass through the credentials but this might not always be what you want to do, especially as PowerShell files are plain text!  There are multiple ways in which we can specify the credentials or store the credentials, its really up to you which you use and which is best suited for your situation.

Continue reading

PowerCLI 5.1 Release 2 Now Available

PowerCLI 5.1 Release 2 has now been released and can be downloaded here.  As always you will find some great new features, bug fixes and enhancements which make PowerCLI even better than before… I know its hard to believe but its true.

VDS Cmdlets

PowerCLI SnapinsWhenever I would ask the question at VMUG’s or VMWorld, “What would you like to see next from PowerCLI” I would always get the same answer “Support for Virtual Distributed Switches!”.

Previously there has been a fling available and also some work created by community member “Luc Dekens” to use VDS, this was a great start but in some cases was not a sustainable solution as it was either not supported or more complicated to maintain or use.

I am now pleased to tell you that PowerCLI has a new snapin, this snapin is called VMware.VimAutomation.VDS and is for managing Virtual Distributed Switches.

Introduced are 14 new cmdlets which will allow you to perform actions against your VDS configuration, we can use the Get-VdsCommand cmdlet to list the new cmdlets.

An overview of these are below:

Cmdlet Name Cmdlet description
Add-VDSwitchPhysicalNetworkAdapter This cmdlet adds host physical network adapters to a distributed switch.
Add-VDSwitchVMHost This cmdlet adds hosts to the specified distributed switch.
Export-VDPortGroup This cmdlet exports the configuration of a specified distributed port group to a specified .zip file.
Export-VDSwitch This cmdlet exports the configuration of a specified vSphere distributed switch to a .zip file.
Get-VDPortgroup This cmdlet retrieves distributed port groups.
Get-VDSwitch This cmdlet retrieves vSphere distributed switches.
New-VDPortgroup This cmdlet creates distributed port groups.
New-VDSwitch This cmdlet creates vSphere distributed switches.
Remove-VDPortGroup This cmdlet removes distributed port groups.
Remove-VDSwitch This cmdlet removes vSphere distributed switches.
Remove-VDSwitchPhysicalNetworkAdapter This cmdlet removes host physical network adapters from the distributed switches they are connected to.
Remove-VDSwitchVMHost This cmdlet removes hosts from the specified distributed switches.
Set-VDPortgroup This cmdlet modifies the configuration of distributed port groups.
Set-VDSwitch This cmdlet modifies the configuration of vSphere distributed switches.

Remember each of these cmdlets has help built in, to access the help including examples of how you might use these cmdlets use the following:

Get-Help cmdletname –full

PowerShell v3 Support

As well as the new cmdlets for working with Distributed switches and all the other great enhancements in PowerCLI 5.1 Release 2 we made sure we listened to our customers and with the release of PowerShell version 3 it seams that a lot of people are already making use or planning to install PowerShell v3.

You will be happy to know that PowerCLI now supports PowerShell v3, this not only gives you support from VMware but also we are now able to take advantage of some of the great enhancements which PowerShell v3 brings.

Some PowerShell v3 examples…

Simplified Syntax… Making PowerShell and therefore PowerCLI easier to read and quicker to type we can use simplified syntax to give us even more English like statements, before we would have needed to use the {} brackets to compare a property, now we are able to type it the same way we would think it…

SNAGHTML26e15701_thumb3

The above simple example shows all virtual machines which are powered on.

vCloud Director 5.1 Support

With PowerCLI 5.1 R2 we have also added support for vCloud Director 5.1, you can now automate the latest version of vCloud director using both PowerCLI and PowerCLI for tenants in a vCloud Director 5.1 environment.

image_thumb2

Let’s Make New-VIProperty Easier

New-VIProperty is a powerful PowerCLI cmdlet and it has been a part of the product since PowerCLI version 4.1. Several releases later, we are under the impression that it is still not widely used. If you take a look around the community, it is easy to find scripts which will would be easier to understand and also work faster if they were refactored to use the New-VIProperty cmdlet.

This blog post is not about how New-VIProperty works. There are several great blog posts on the internet which already explain how the cmdlet works and what its benefits are. Some of them are:

We understand that using New-VIProperty is not that easy. There are a lot of things that should be considered when you create a property – the name of the type you want to customize, the name of the API property, etc.

This blog post includes a PS module whose purpose is to make the use of New-VIProperty easier, the module can be downloaded from here.

Once you import this module into your PowerCLI session, you will be able to:

  • Benefit from tab-completion for the New-VIProperty cmdlet
  • Inspect which types are customizable with New-VIProperty
  • Inspect the properties of a particular customizable type in depth

Let’s take a look at the tab-completion feature

We can start creating a new property by entering “New-VIProperty –ObjectType“. Then, if we press the Tab key, we will iterate through the valid values for the ObjectType parameter.

clip_image002

Of course, when we know the first letters of the type we want to customize, we can enter them before pressing the Tab key. In this case, pressing the Tab key will iterate only through the types whose names start with the provided letters.

clip_image004

In the screen above, pressing the Tab key will show types like VirtualMachine, VirtualPortgroup, VirtualSwitch, etc.

If we are creating a value-based property, after the type has been defined, we should specify the API property with the –ValueFromExtensionProperty parameter. Now this is much easier using tab-completion.

clip_image006

So the type is VirtualMachine, and let’s say we want to add ToolsVersion. It is part of the Guest API property. So we can just enter “G” and then press Tab key. This time the tab-completion feature will search for all properties starting with “G” within the VirtualMachine backing API type. The first match is “Guest”.

After that we should add a dot and start pressing Tab until the desired property appears.

clip_image008

The Guest property has several sub-properties and after several hits on the Tab key we will reach the “ToolsVersion” property. The only thing left to do is give our new property a name. We will do this manually.

clip_image010

Tab-completion also works for the –BasedOnExtensionProperty parameter when you are creating a script-based property.

The second enhancement is the ability to retrieve the list of customizable types

The provided PS module exports the Get-VIPropertyValidTypeNames function. By default, it returns the complete list of types which we can customize using New-VIProperty.

Each type is represented by a PSObject with the following properties:

  • TypeName – represents the string that New-VIProperty accepts through the ObjectType parameter
  • IsManaged – indicates whether the backing API type is managed or not. For more information about managed and data object types, see the vSphere API SDK documentation
  • VimTypes – a list of the backing API types. Knowing which is the backing type of a cmdlet type could be useful; for example, we can refer to the vSphere API SDK documentation for a more detailed description of the API type.

clip_image012

The function provides three filter parameters which let you reduce the list of types. Run “Get-Help Get-VIPropertyValidTypeNames” for more information.

The last enhancement is another function named Get-VIPropertyHelperObject.

This function accepts the name of a customizable type and returns a helper PSObject which could be used for:

  • Inspecting the backing API type
  • Searching API type properties by name
  • Creating VI properties easily

Let’s see this in action. Let’s pass VMHost to the function and save the result in the $helper variable.

The structure of the helper object is based on the backing API object. It has the same set of properties, but their purpose is informative. The output of this object looks like this:

clip_image014

At the top we can see the cmdlet type –VMHost – and the backing API type – HostSystem.

The list of all API type properties follows. For each property, the type is also displayed.

A plus symbol in front of the property indicates that it has sub-properties and it is browsable. For example, if you write $helper.Config, you will see all the properties of Config.

clip_image016

The helper object also has a method named SearchProperties. It searches all properties and sub-properties by name.

Let’s assume that we want to add a property to all VMHosts which shows the vendor of the hardware box. We also know that there is a ‘Vendor’ property in the API object, but we are not sure where it is defined, so we can call $helper.SearchProperties(‘Vendor’).

clip_image018

The output contains all properties whose names contain ‘Vendor’. The last one is the property that we’re looking for.

The next step is creating a property and this is really easy with the helper object. The only thing that we have to do is to call this line: $helper.Summary.Hardware.Vendor.CreateValueProperty()

The helper object provides an identical method for each property within the whole structure. This method creates a VI property using the New-VIProperty cmdlet.

clip_image020

We can see that the method first shows the New-VIProperty expression which will be executed. Below this line, you can see the result of running the New-VIProperty cmdlet.

Let’s see the result of our actions:

clip_image022

This method is really useful for an interactive PowerCLI session, but what about if we want to create a VI property within a script. The helper object provides two methods named GetValuePropertyCreationCode and GetScriptPropertyCreationCode.

Both methods build and return a New-VIProperty expression which you can copy, paste and modify in your script.

clip_image024

Three of the methods have a parameter which accepts the name of the new VI property. If it is not specified (as it is not in the examples), a name will be selected automatically.

Summary

In conclusion, this module allows you to:

  • Inspect API types easily and search their properties by name
  • Create VI properties or generate New-VIProperty expressions to use in a script
  • Retrieve the list of customizable types
  • Use tab-completion within the New-VIProperty cmdlet

Finally, let’s see where New-VIProperty is applicable and why it is better to use:

    • If you have a Select expression using hash table syntax
      • Get-X | Select-Object -Property Name,@{Name=”NestedPropertyName”;Expression={<some expression over $_>}}
    • If your script needs data from the ExtensionData/View
      • foreach ($vm in $vms) { ….. $foo = $vm.ExtensionData.foo …..}
    • The code look better
    • The scripts are faster

Download

Download the module from here and import it into your session.

What Next?

If you find this module helpful or have any other comments on this feature we would love to hear them, the PowerCLI team at VMware constantly tries to make PowerCLI a better product and a product which is easy to use, let us know what you think of this and if you would like to see things like this backed into the release of PowerCLI.

 

imageThis post was created by Vitali Baruh…

Vitali joined VMware and PowerCLI team in the beginning of 2009. He is member of the quality engineering part of the team and his main role is the functional verification of the vSphere, vCloud and License PowerCLI components.

As all members of the team he is working to deliver a good and valuable product. He is also working to improve all processes and tools involved in product development and validation.

PowerCLI 5.1 and the future

Recently I have had some questions from people using PowerCLI, these are mainly related to confusion around the 5.1 release of VMware products and the way that PowerCLI works so I wanted to use this blog post to answer some of these questions but also to confirm that the future for PowerCLI is bright.

Q.  “Does PowerCLI work with the vCenter Server Appliance?”image

A. Yes it does, PowerCLI uses the vCenter APIs, in fact the best place to install PowerCLI is the same place that you would use the vSphere Client from, this is normally the vSphere admins workstation or a windows machine used solely for scheduled tasks.  PowerCLI connects to the vCenter APIs and therefore both Windows and the appliance versions of vCenter work with PowerCLI 5.1.

Q. “Does PowerCLI work with the vSphere Web Client?”

A.  A common question and yet in reality you do not need the C# vSphere Client or the vSphere Web Client in order for PowerCLI to work, everything you need is inside the installer for PowerCLI, just install it (instructions here) and your set.

Q. “With VMware releasing more and more Linux related appliances what does this mean for PowerCLI?”

A. PowerCLI is one of VMware’s most successful and well loved automation and troubleshooting tools by vSphere and vCloud Director Admins, as I said in the answer to a previous question, it connects directly to the vSphere APIs, it doesn’t care what is hosting them.

Whilst I can not discuss the roadmap for PowerCLI I can certainly say its as strong as ever and we will continue to wow the users of PowerCLI with the latest features and updates.

Q. “Does Onyx work with vSphere 5.1?”image

A. For those of you who are not aware of what Onyx is, it’s a VMware Fling which sits in-between your vCenter and your vCenter Client, it intercepts the traffic and translates it into PowerShell code, not nicely formatted PowerCLI type cmdlets but still a great place to look if you need to find a way to do something quickly.

You hit play on the Onyx client and the fun begins, anything you do in the vSphere client from then on is captured and represented as code, and not just PowerShell code but also C#, vCO JavaScript and  Raw SOAP messages.

So does it work with 5.1 ?  Yes of course it does, but only when using the C# client, obviously the vSphere Web Client works differently and therefore Onyx is unable to capture the actions you take in the web client and turn them into code, as this is a fling I can not make any promises of if or when this will be updated to work with the web client but obviously the challenges are different.  In the meantime make sure you use the C# client when you want to capture the code.


Hopefully this will help eliminate any questions about PowerCLI and how it works with 5.1 and the future, if you have any further questions please add a comment to this post and we will do our best to answer them.