Get-view, list viewtypes, filter usage, Get-VIObjectbyVIView, and get-vm in powercli


From time to time i check my blog to see how people are getting to my blog 😉 Today i thought that if so many of you are trying to find this information although for some reason it is not in that post to which you are being redirected, i will create a new post about it. So that you will not be disappointed that the information is not there.
So few things about get-view. I think that VMware offers a GREAT documentation so why not take their explanation 😉

The vSphere PowerCLI list of cmdlets includes the Get-View and Get-VIObjectByVIView cmdlets, which enable access to vSphere PowerCLI views from .NET.

Using the vSphere PowerCLI views cmdlets for low-level VMware vSphere management requires some knowledge of both PowerShell scripting and the VMware vSphere APIs.


In few words… While installing powercli you receive a set(a great set 😉 ) of cmdlets. You can get info about vms,datastores,clusters etc, etc… You can run verb cmdlets like set/new/invoke/move/restart/start/stop etc, etc.. well you can see it yourself executing ‘get-vicommand’ how many of those there are 😉 But in case that’s not enough you can access vsphere objects using views. You will discover that they provide even more options than cmdlets. Some things can’t be done using powercli cmdlets, and they need to be executed using views and their methods. Views also provide access to specific managers like license manager, alarm manager etc…

$Si = Get-View ServiceInstance
$Si.content  # would list available managers

I think that the most common mistake in my opinion is to get the view from get-vm. Well i was doing it myself too 😉

$MyVMsViews=get-vm|get-view

So then i could have an array with all views.
Now this not necessary to pass get-vm objects via pipeline to get-view. It works ok, but get-view can get virtual machines on it’s own.

$MyVMsViews=get-view -viewtype virtualmachine

There 😉 1 command. You can ask now how did i know that there was a viewtype like this. For example :
get-vm -name testvm
takes 1 second and 994 milliseconds
where
get-view -viewtype virtualmachine -filter @{‘name’=’testvm’}
takes 0 second and 455 milliseconds
Those measurements were taken on a small scale infra ~1000 vms.

Get-vm and get-view for vm. Get-view will provide us additional methods:
Name MemberTy
—- ——–
AcquireMksTicket Method
AcquireTicket Method
AnswerVM Method
CheckCustomizationSpec Method
CloneVM Method
CloneVM_Task Method
ConsolidateVMDisks Method
ConsolidateVMDisks_Task Method
CreateScreenshot Method
CreateScreenshot_Task Method
CreateSecondaryVM Method
CreateSecondaryVM_Task Method
CreateSnapshot Method
CreateSnapshot_Task Method
CustomizeVM Method
CustomizeVM_Task Method
DefragmentAllDisks Method
Destroy Method
Destroy_Task Method
DisableSecondaryVM Method
DisableSecondaryVM_Task Method
EnableSecondaryVM Method
EnableSecondaryVM_Task Method
Equals Method
EstimateStorageForConsolidateSnapshots Method
EstimateStorageForConsolidateSnapshots_Task Method
ExportVm Method
ExtractOvfEnvironment Method
GetAllEventsView Method
GetAllTasksView Method
GetEntityOnlyEventsCollectorView Method
GetEntityOnlyTasksCollectorView Method
GetEventCollectorView Method
GetHashCode Method
GetTaskCollectorView Method
GetType Method
MakePrimaryVM Method
MakePrimaryVM_Task Method
MarkAsTemplate Method
MarkAsVirtualMachine Method
MigrateVM Method
MigrateVM_Task Method
MountToolsInstaller Method
PowerOffVM Method
PowerOffVM_Task Method
PowerOnVM Method
PowerOnVM_Task Method
(…)

Whereas get-vm will provide us an object to use with other cmdlets, no methods like above at all. One more thing about this last sentence. Since PowerCLI 4.1 you can access those setting via get-vm as well. Extensiondata object was introduced. And if you need to access properties from views, you do:
(get-vm test1).Extensiondata
which will act in the same way as get-view -viewtype virtualmachine -filter @{‘name’=’test1’}
So now if you need to take some property value from the view, and you have already some object from get-vm there is no need to pipe it to get-view. Instead you can access that property directly like:

(get-vm test1).Extensiondata.Guest.ToolsStatus

That will be the same as with using get-view approach:

(get-view -viewtype virtualmachine -filter @{'name'='test1'}).guest.toolsstatus

Ok so Greg… now you are confusing ME !!!!!!!!!!!!!!!!!!!!!
– I know , i am sorry ! 😉
For reporting purposes i would choose approach with get-view only, due to performance boost. It executes way faster than having data from get-vm checked and filtered.

get-view -ViewType virtualmachine -Filter @{'guest.toolsstatus'='toolsNotInstalled'}|select name

That would take 658 milliseconds on small scale infra to complete.

get-vm|?{$_.extensiondata.guest.toolsstatus -eq 'toolsNotInstalled'}

That would take 1 minute and 58 seconds to complete. The result is the same, we have queried for vms that run without vmware tools. The difference is in time it took to present this data.
Get-view by default will also include templates when asked with virtualmachine viewtype. You can exclude that using filter

get-view -ViewType virtualmachine -Filter @{'guest.toolsstatus'='toolsNotInstalled';”Config.Template”=”False”}|select name

Now the number of vms returned should be equal to number of vms returned from get-vm.

Viewtype from get-view supports those views:
ComputeResource, ClusterComputeResource, Datacenter, Datastore, Network, DistributedVirtualPortgroup, DistributedVirtualSwitch, Folder, HostSystem, ResourcePool, VirtualApp, VirtualMachine, VmwareDistributedVirtualSwitch

(get-cluster|select -first 1).extensiondata.moref

Type                                    Value
----                                    -----
ClusterComputeResource           domain-c322

(get-vmhost|select -first 1).extensiondata.moref
Type                                    Value
----                                    -----
HostSystem                              host-1944
(get-vapp|select -first 1).extensiondata.moref

Type                                    Value
----                                    -----
VirtualApp                              resgroup-v4996

So the type can be read from moref, which is managed object reference object. What also should work (but at this time it is not working for me ;( ), you can try to run ‘get-view -viewtype xyz ‘ , it will force get-view to tell you what views does he support. For some reason it is not working for me when i am using powercli 5.x . It returned those values in previous versions though 😉

So, in order to get different views than virtualmachine:
get-datastore but using view: get-view -viewtype datastore
And so on and on… I hope that by now you will still remember about our Extensiondata 😉 (get-datastore “ds01”).Exensiondata
About filters for get-view.
Like in example: get-vm -name t*
would return all vms that start on letter t, we can do the same with get-view using filters

get-view -viewtype -filter @{'name'='^t'}

Filter is descirbed in manual for vsphere manual documentation

The filter parameter is a HashTable object containing one or more pairs of filter criteria. Each of the criteria consists of a property path and a value that represents a regular expression pattern used to match the property.

Note that all filter parameters must mach.You can use regex inside filter. ‘name’=’^t’ would indicate that FIRST letter should be t.
Ok, lets filter it more. I want views from vms that start on letter t, and they are powered on

$view=get-view -viewtype virtualmachine -filter @{'name'='^t'}
$view|%{$_.summary.runtime}  

You can check what’s the actual powerstate from this property, so we can use it in our filter

get-view -viewtype virtualmachine -filter @{'name'='^t';'summary.runtime'='poweredon'}

Ok but let’s say that you are looking for vms that start on letter t and L . So how are we supposed to put t AND L in the same name filter?
Since you are using regex there, you can apply OR

get-view -ViewType virtualmachine -Filter @{'name'='^t|^L'}|select name

One more question could be :
Ok, i want to use my get-view on some specific location like clusterA:
get-view -viewtype virtualmachine -SearchRoot (get-cluster -name ‘clusterA’).id
where SearchRoot is :”Specify a starting point for the search (in the context of the inventory).” taken from vsphere documentation
😉 and so on and on. When you want to attach your query to some location use the -SearchRoot switch

One other thing. So let’s say that you are in middle of doing “stuff” on objects from get-view. And for some reason you want them to interact with powercli cmdlets. If i would take now my view object $myvm=get-view -viewtype virtualmachine -filter @{‘name’=’testvm’} and would like to start it or stop it using powercli cmdlets like start-vm, stop-vm, it will not work. It works only with virtual machine objects returned from get-vm, not from views. But VMware gave us additional cmdlet to help us out in those situations.

$myvm|stop-vm
Stop-VM : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its prop
erties do not match any of the parameters that take pipeline input.
At line:1 char:12
+ $a |stop-vm <<<<
    + CategoryInfo          : InvalidArgument: (VMware.Vim.VirtualMachine:PSOb   ject) [Stop-VM], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,VMware.VimAutomation.ViCore.
   Cmdlets.Commands.StopVM

$testvm | Get-VIObjectByVIView |start-vm

Name                 PowerState Num CPUs Memory (MB)
----                 ---------- -------- -----------
testvm               PoweredOn  1        4096

There 😉 It works now ! So how get-viobjectbyviview has helped us ?

Converts a vSphere View object to a VIObject using the object ID provided by the MoRef parameter. If the View object is a ServiceInstance, you cannot convert it to a VIObject.

From the moment that object leaves get-viobjectbyviview it will become the same virtualmachine object as it would come from get-vm testvm. And we can now use with other powercli cmdlets.
When can i apply this command ? Ok , i will give now 1 example. You probably know that running get-snapshot will take a while in bigger infra right ?
We can still query for vms with snapshots using get-view with filter:
Get-View -ViewType VirtualMachine -Filter @{“snapshot” = “”}
This will output view for vms that have snapshot. That’s cool, but what’s next if you can’t pipe this output to remove-snapshot cmdlet. Get-VIObjectbyVIView ! Bingo 😉
Get-View -ViewType VirtualMachine -Filter @{“snapshot” = “”}|Get-VIObjectbyVIView|get-snapshot
You can then interact with those objects using powercli cmdlets.
One more thing, the powercli version 5.0.1 build 581491 has problem with running get-viobjectbyviview . Either update your powercli version or make a tiny fix 😉

Get-View -ViewType VirtualMachine -Filter @{"snapshot" = ""}|%{$_.moref|Get-VIObjectbyVIView|get-snapshot}

In order to fix that i had to pass manually moref to get-viobjectbyviview.

I hope this post explains a little bit of differences between get-vm and get-view. If you have any questions please post a comment and i will update the post then.
Another post that i wrote recently that explains it as well https://psvmware.wordpress.com/2014/02/02/find-cpu-hogging-vms-using-powercli/

Advertisements

19 thoughts on “Get-view, list viewtypes, filter usage, Get-VIObjectbyVIView, and get-vm in powercli

  1. Good article. One thing I can’t seem to find on the web is what are ALL the available filters for the get-view command. What documentation is this information found on?

    Here are a few filters I have used but where do I find complete list.

    Get-View -ViewType VirtualMachine – Filter @{“Summary.Guest.ToolsVersionStatus” = “guestToolsNeedUpgrade”}

    Get-View -ViewType VirtualMachine – Filter @{“Runtime.PowerState” = “PoweredOn”}

    Get-View -ViewType VirtualMachine – Filter @{“snapshot” = “”}

    Running the command Get-View -ViewType virtualmachine | get-member gives me the available methods and property for Get-View but no information on available filters.

  2. Hi, i don’t think that you will find somewhere a complete list of filters. Manual explains it in a way that tells you that you can pass there object property and it’s value. Therefore you would have to have a list of all possible properties i guess. Take a look on the manual here :
    http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-View.html It simply says that you can use property. So if you have a view of properties that you got from get-view ran against a vm for example, you could use any property and it’s value in the filter. Filter also uses regex, so you can create your own query in it. quick example , if you need to find vms with vm hw version 7 you would need to take a look where this info is stored so: $a=get-vm vm1|get-view , then $a.config.version will tell you what hw is this vm running. So you can use this property in the filter like this
    Get-View -ViewType VirtualMachine -Filter @{“config.version” = “vmx-07”} | select name
    for example. so basically i guess that you can use majority of properties that you see in the properties for an object.
    1. do get-view on an object
    2. take a look on available properties, note down the whole name of property
    3. use filter on it with hashtable ‘full.prop.name’=’value1’
    I notice sometimes that some properties will not work, for example, if you will have view for vm, and it’s property : parent, then filter will not work but in this case you should use the -SearchRoot parameter
    so
    Get-View -ViewType VirtualMachine -Filter @{“Parent” = “Folder-group-v329”} | select name
    this will not work but
    Get-View -ViewType VirtualMachine -Searchroot Folder-group-v329 | select name
    will work.
    Let me know if you have any other questions.

  3. Pingback: VCAP5-DCA Objective 8.1 – Execute VMware Cmdlets and Customize Scripts Using PowerCLI
  4. Pingback: VCAP5-DCA Objective 8.1 – Execute VMware Cmdlets and Customize Scripts Using PowerCLI
  5. Just came across this article when searching for “Cannot run Get-Templates”. So I am rather new to PowerCLI and I am attempting to run functions such as Get-Sessions, Get-Templates, and just learning as I go. When I try and take it back to the beginning and learn from posts such as yours I am unable to execute these commands and I see the below for example…

    PS C:\Users\tlewey\Desktop> Get-Sessions
    The term ‘Get-Sessions’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check th
    e spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:13
    + Get-Sessions <<<<
    + CategoryInfo : ObjectNotFound: (Get-Sessions:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Hope this is not too much of a newb inquiry, thanks for the blog post.

    Todd

    • Hi Todd,
      try ‘get-template’ and not : ‘get-templates’ . General rule in powershell is that or nouns should be singular .
      There is no get-sessions cmdlet. What do you want to achieve with it ? you want to see sessions list ?
      (Get-View SessionManager).sessionlist
      like this ?

  6. Nice overview … so i was trying to play around with this..
    CreateScreenshot i found in “Get-View -ViewType virtualmachine | get-member”

    Now how to fit that in below ?
    $vm = Get-View -ViewType VirtualMachine -Filter @{“Name” = “my-vm”}

    thanks

  7. psvmware i forgot the context of my Q 😛

    But i have new Q now :

    We can see extension data
    “Guest : VMware.Vim.GuestInfo”

    Then you mentioned, we can use “guest.toolsstatus”

    Now how can we find what else we can use with Guest.”???????”

    Thanks

  8. Hi,

    I am trying to use the Get-VM command to find VM’s in my Environment that start with dc1dtl* by using (Get-VM -Name dc1dtl* | Out-file c:\test.txt) I can get this to work but I get an output with the headings “Name”, “Powerstate” ,”NUM”,”CPUs”,”MemoryGB” and all those values. I just want to filter it so I have a text file with just the names, how would I do that?

    Thanks i’m still new to Powershell.

    • Get-VM -Name dc1dtl* | select-object name| Out-file c:\test.txt , or (Get-VM -Name dc1dtl*).Name > c:\test.txt

  9. Pingback: Getting VM Information using Get-view | Welcome to deepakkanda's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s