PurpleScreen blog about open source

The power of Get-View

Today we’re going to discover very powerful Get-View cmdlet. I’m sure most of you have seen it in many scripts found across the web. This cmdlet returns .NET view objects thus exposing API methods and properties to PowerShell environment. This is crucial in advanced manipulating with vSphere infrastructure.

First, it’s worth mentioning that getting implementation objects (those produced by Get-VM, Get-VMHost, etc) takes more time than getting view objects, though in the last versions I found the gap decreased significantly. Let’s discover the available parameters that need to be discussed:

-VIObject, -Id

View object can be retrieved by MoRef -Id or by passing the impl object -VIObject to the cmdlet. Don’t forget to use -Server parameter when retrieving objects by MoRef if you are working with multiple default vCenter servers since MoRefs are not unique across different vCenter servers.

-Property

This parameter allows you to limit the object properties to be retrieved and can significantly speed up the query execution. Going ahead, one interesting thing you may wonder while using this parameter together with -Filter: does the property that objects are filtered by need to be specified here? The answer is no, they do not.

-Filter

This parameter accepts a hash table: @{Name='^TestVM[1-9]$'; 'Config.Version'='7'; 'Snapshot'=''}, where both keys and values represent the strings and imply that for any object returned every specified key must match the corresponding value. The key can be any nested property but not the property of linked object - for linked objects use -SearchRoot parameter (more on that later). You can use the power of regular expressions for value strings. You may wonder how to test whether the property exists for the object? Just specify this property with the empty value. The example above will filter all vms with name matching TestVM, hardware version equal to vmx-07 and for which at least one snapshot exists.

Filtering on the server side prevents the objects that don’t satisfy the specified criteria to be transfered to the client, thus it again increases the performance.

-ViewType

The parameter allows you to query for object of a specific type. To learn more about types, inheritance and so on go to API reference guide.

Another really useful types of objects that can be retrieved by Get-View are different types of managers. The full list can be obtained with (Get-View ServiceInstance).Content call.

One can use them to manipulate alarms (Get-View AlarmManager), tasks (Get-View TaskManager), files and so on. So it’s very useful stuff too.


Ok, this part is done. Now let’s explore the base view object. We have an interesting liaison here: UpdateViewData() method and .LinkedView property.

Until UpdateViewData() is invoked, the .LinkedView property is empty. Parameters of UpdateViewData() invocation are (multiple) properties of the current or linked object you want to obtain. Together with a property name, we can specify a property object type. In some cases it’s quite useful to restrict the possible values, if the property is the list of object of different types. Let’s see an example: consider navigating through inventory folders - every time you want to get the child objects, but only those of type Folder:

$FolderView = Get-View -ViewType Folder -Property Name -Filter @{Name='RootFolder'}
# The call will retrieve ChildEntity property for the current folder. No linked views are populated
$FolderView.UpdateViewData('ChildEntity')
# The call below will fill the LinkedView property
$FolderView.UpdateViewData('ChildEntity.*')
# or you can restrict the child objects retrieved to folders with only Name and ChildEntity properties obtained
$FolderView.UpdateViewData('[Folder]ChildEntity.Name','[Folder]ChildEntity.ChildEntity')</pre>

The type restriction is neccessary when you specify the property path that include containers and this property doesn’t belong to all entities a container can include. Thus $FolderView.UpdateViewData('ChildEntity.ChildEntity') won’t work because folder can include vm objects for which ChildEntity property isn’t defined.

Got it? Then another example of digging even deeper:

$VmView = Get-View -ViewType VirtualMachine -Property Name -Filter @{Name='TestVM'}
$VmView.UpdateViewData('Runtime.Host.Datastore.Name')
# will extract the names of all datastores connected to host where vm is currently running
$VmView.Runtime.LinkedView.Host.LinkedView.Datastore.Name

So, instead of calling Get-View multiple times you can leverage UpdateViewData() method call. It really accelerates your scripts where you need to get nested view objects.

Now that you are aware of the foundation of advanced PowerCLI scripting, use Get-View in your scripts when processing the bulk of data and the speed is a vital factor. When operating few objects stay with common impl-getting cmdlets not to loose the simplicity of your scripts.

PowerShell scheduled job output redirection

Scheduling the script execution is rather common task. You might know that it’s possible to manage scheduled tasks in PowerShell with built-in ScheduledTask module cmdlets. To keep track whether the task run successfully or not it’s quite useful to redirect the output of the script to a file. PowerShell allows output redirection for all stream types (standard/error/warning/etc), see TechNet about_Redirection help topic.

To be able to run your scripts with -Verbose option you should leverage Advanced_Functions syntax (see another Core About topic). Just add couple of strings to the beginning of the script:

[CmdletBinding()]
param()

and use Write-Verbose cmdlet throughout the script where chatty output is needed. At first glance it seems to be an easy task to combine all the mentioned together, but in fact I saw lots of questions across the web where people struggled to make it work. Indeed, it took much effort before I succeeded. I’ve tested many different configuration and most of them didn’t work for me too. That’s what I came up with and it worked for me:

Register-ScheduledJob .. -ScriptBlock { C:\Scheduled.ps1 -Verbose *> 'C:\Scheduled.log' }

vCenter Converter 5 low processing rate

If you experience too slow conversion speed while doing P2V migration or other conversion task and see no reason for this, the solution might be to disable SSL encryption for data transfers between the agent and the server. To accomplish this open the file C:\ProgramData\VMware\VMware vCenter Converter Standalone\converter-worker.xml and disable SSL:

<nfc>
  <useSsl>false</useSsl>
</nfc>

Restarting Converter Worker service is required. Hope this helps!

ForEach: cmdlet vs keyword

Here is a little note about the difference of these two loop constructions.

foreach is a reserved keyword in PoSH that allows you to loop through collection of objects and make some action on every item. Inside the foreach loop $foreach automatic variable is available. It presents the loop enumerator and can be used, for instance, to skip the current object in collection (.MoveNext() method).

ForEach-Object is a cmdlet doing almost the same thing but the difference is the usecase. Since the collection is piped to the cmdlet the objects are pushed down the pipeline as soon as they are generated. It affects the performance greatly when a collection isn’t created at the start of processing. When the last is long-time operation using the cmdlet you can achieve much better overall performance than using its brother-keyword. In other case one should consider using the keyword for higher execution speed.

Since both have the same alias foreach the PoSH parser is smart enough to select the appropriate construction depending on the place it is used.

VMware UUIDs

Hi everybody! My first post is about UUIDs - identifiers used for virtual machines in vSphere infrastructure. If you ever looked in vm config file (*.vmx) you could see 3 different lines containing 128-bit hex numbers. They are:

  • uuid.bios
  • uuid.location
  • vc.uuid

Because of having some issues with software licensing inside guest OS I decided to explore what the every value is responsible for. Web hasn’t gave me the complete answer about the meaning of all of these parameters so my investigations led me to the following conclusion I’d like to share with you.

uuid.bios - this value acts as GUID analog in physical machine, you should keep it to make the license not to get broken. If you want to export VM, for example using vCenter Converter, and run it in VMware Player/Workstation you should also add the following line to exported vmx file together with copying the source uuid.bios value: uuid.action = "keep"

It prevents player/workstation from asking whether you moved or copied VM with default answer I moved it. If the valid uuid.bios line is present in config file it will be preserved and the software license will be OK. Another option for uuid.action is change. In this case VMware will generate the value when you power on VM in new location (host or even folder). You can read this KB article to learn more about it. So the uuid.bios setting is done. Let’s look through others two.

uuid.location is generated every time VM is vMotion’ed to another host/storage. I guess it’s used by vCenter for some internal purposes like ..

vc.uuid is used by vCenter to identify VM together with MoRef ID you’ve seen while working with PowerCLI. It’s unique and is generated when you add VM to inventory (or create VM). If the value is already present in config file (and there is no duplicate in current inventory) it’s left intact.

That’s enough for the first post. In the end - a little piece of PowerShell code to automate the postprocessing of exported VM to ensure its uuid.bios value is the same as source vm’s. It guarantees the persistence of all licenses that depends on GUID.

Stay tuned, keep learning!