Get-gEvents for getting vsphere events with some additional filtering

Some time ago i wrote a dirty function that utilizes eventfilterspec to filter out events. I knew it had one flaw, because as far as i remember i was using there QueryEvents method. Nothing bad with that, but as far as i understand it will only return up to 1000 records. So i have finally modified it so it uses EventCollector. It has support for searching by eventchainID, eventTypeId, username, date. I have tried to document function as much as possible. For me it works ok. There is some tiny support for checking eventTypeIds inside the function. If something is not clear make sure you will read the help
get-help get-gEvents -full
One confusing bit might be that while passing the entityname , you have to pass the viewtype as well. Well i did it because i use it this way 😉 So i use Get-View -ViewType [type] -Filter @{‘name’=XXX’}
So it’s up to you what exactly you are looking for, while specifying the entity, In filter name will be put, but ViewType specifies the type of object, whether it will be a datacenter, vm , cluster, datastore etc..
I tried to implement the switch for enabling/disabling full formatted message, but for some reason it was not working, no idea why.

Quick examples:

How to check how many vmotions DRS has performed inside a particular cluster ?

(Get-gEvents -StartDate (get-date).AddDays(-1) -types 'VmBeingHotMigratedEvent' -EntityName 'Cluster_name' -ViewType ClusterComputeResource).Count

How to check how many vmotions DRS has performed inside a particular datacenter ?

(Get-gEvents -StartDate (get-date).AddDays(-1) -types 'VmBeingHotMigratedEvent' -EntityName 'Datacenter_name' -ViewType Datacenter).count

Endless possibilities basically.. i will throw 1 more
How many times user X has powered off a VM in last 7 days

(Get-gEvents -StartDate (get-date).AddDays(-7) -EventTypeIds 'VmPoweredOffEvent' -EventUsername 'DOMAIN\UserX' -systemUser:$false ).count

How many were there vmotions in some cluster during last 7 days

Get-gEvents -StartDate (get-date).AddDays(-7) -EventTypeIds 'VmFailedMigrateEvent' -EntityName 'SomeCluster' -ViewType ClusterComputeResource}

What if you want to check for other dates ? Use: -StartDate with (get-date).AddDays(-7) for example, to go 7 days back. Same goes for end date, -EndDate (get-date…..

When you will be giving parameter for the Entity, you can still use the -Recursion parameter with it to control whether you want to inspect only THAT entity, or its children, or both.

If you will skip -startdate or -enddate make sure you know that function is setting those variable up anyway with default values of: Enddate -> NOW , -startdate 7 days ago.

Make sure you know that by default if you will skip those parameters : systemuser and recursion will be set to true and all . So if you wonder how come you received system events if you were looking for user’s events, mark the -systemuser:$false , if you want to look only for event on entity and do not want to step inside its children use -recursion ‘self’ , because by default i set it to ‘all’.

You do not need to provide entity for this function to start, if not given it searches through everything.


function Get-gEvents
  <# .SYNOPSIS Get-gEvents is utilizing EventCollector to get information about events. .DESCRIPTION Get-gEvents utilizies most of what EventCollector has to offer. If Start or End date is not specified, the default values of: End - Now, Start - last 7 days will be applied. If you are using EventUserName parameter, you can then choose SystemUser parameter. By default it is selected as True, so if you do not want to see system events please set it to -SystemUser:$false , so you will get only user's records. This function also allows to get current list of types for events, if you do not remember a particular event, first try this function with -ListMainEVTypes From there you can use -ListSecEVTypes with -SubEVType and give it value of name of typse from previous command. .EXAMPLE Count DRS vmotions in Virtual Center for last day. (Get-gEvents -StartDate (get-date).AddDays(-1) -EventTypeIds 'VmBeingHotMigratedEvent').count .EXAMPLE Get-gEvents -ListSecEVTypes -SubEVType 'VmEvent' .PARAMETER ListMainEVTypes If used , you will received main event types categories. .PARAMETER ListSecEVTypes If used, you have to use SuvEVType to select the right subcategory to expand. .PARAMETER SubEVType From output of -ListMainEVTypes you can paste its name to -SubEVType , in response you will get more detailed event types. for example -SubEVType 'VmEvent' .PARAMETER eventChainId If you are interested only in particular event chain you can specify it's id here. .PARAMETER EventUsername You can search only user's events by giving in this parameter the login of user for example: 'userX', 'DOMAIN\UserX' .PARAMETER EntityName Name of the entity for which or underwhich you will be looking for events. It works together with ViewType. .PARAMETER systemUser In use with EventUsername, By default systemUser is $True, so that you will see the user's and the system events. If you will give -systemUser:$false then, only user's events will be gathered. .PARAMETER EventTypeIds This parameters can handle multiple ids of eventtypes separated by comas, for example : VmBeingHotMigratedEvent for checking drs migrations or VmPoweredOffEvent for vms getting powered off. If you do not know the specific type id, you can always run this function with ListMainEVTypes and ListSecEVTypes paramegters to get hints. .PARAMETER category Possible categories are: info, warning, error, user. .PARAMETER StartDate Start date for the search query. For example (get-date) for now, or (get-date).AddDays(-1) for yesterday. .PARAMETER EndDate End date for the search query. For example (get-date) for now, or (get-date).AddDays(-1) for yesterday. .PARAMETER Recursion You can choose from Self,Children,All options. Self is only checking events on Entity itself, Childred only on Children entities, and all is Self+Children. .PARAMETER ViewType This is the ViewType that you would normally use within Get-View to find that particular entity. For example HostSystem for host, or VirtualMachine for VM, or ClusterComputeResource for Cluster. .LINK .NOTES Author : Grzegorz Kulikowski #>
	[cmdletbinding(DefaultParametersetName = "Main Usage")]
	param (
		[parameter(Mandatory = $true, ParameterSetName = "Main Events Types Listing")][switch]$ListMainEVTypes,
		[parameter(Mandatory = $true, ParameterSetName = "Detailed SubEvents Types Listing")][switch]$ListSecEVTypes,
		[parameter(Mandatory = $true, ParameterSetName = "Detailed SubEvents Types Listing")]$SubEVType,
		[parameter(Mandatory = $true, ParameterSetName = "ChainID Events Listing")][string]$eventChainId,
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][string[]]$EventUsername,
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][bool]$systemUser = $true,
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][string]$EntityName,
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][String[]]$EventTypeIds,
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][VMware.Vim.EventCategory]$category,
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][datetime]$StartDate = (Get-Date).AddDays(-7),
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][datetime]$EndDate = (Get-date),
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][vmware.vim.EventFilterSpecRecursionOption]$Recursion = 'all',
		[parameter(Mandatory = $false, ParameterSetName = "Main Usage")][ValidateSet('ClusterComputeResource', 'ComputeResource', 'Datacenter', 'Datastore', 'DistributedVirtualPortgroup', 'DistributedVirtualSwitch', 'Folder', 'HostSystem', 'Network', 'OpaqueNetwork', 'ResourcePool', 'StoragePod', 'VirtualApp', 'VirtualMachine', 'VmwareDistributedVirtualSwitch')][string]$ViewType
	switch ($PsCmdlet.ParameterSetName)
		"Main Events Types Listing"  {
			[VMware.Vim.VmEvent].Assembly.GetTypes() | ? { $_.BaseType -eq [VMware.Vim.Event] }
		"Detailed SubEvents Types Listing"  {
			[VMware.Vim.VmEvent].Assembly.GetTypes() | ? { $_.BaseType -like "VMware.Vim.$SubEVType" }
		"Main Usage" {
			$si = get-view -id ServiceInstance
			$em = get-view -id $si.Content.EventManager
			$EventFilterSpec = New-Object VMware.Vim.EventFilterSpec
			$EventFilterSpec.eventTypeId = $EventTypeIds
			if ($StartDate -or $EndDate)
				Write-debug "Date was given"
				$EventFilterSpec.Time = New-Object Vmware.Vim.EventFilterSpecByTime
				$EventFilterSpec.Time.beginTime = $StartDate
				$EventFilterSpec.Time.endTime = $EndDate
			if ($category)
				Write-debug "Category was given"
				$EventFilterSpec.Category = $category
			if ($EventUsername)
				Write-debug "User was given"
				$EventFilterSpec.userName = New-Object Vmware.Vim.EventFilterSpecByUsername
				$EventFilterSpec.userName.systemUser = $systemUser
				$EventFilterSpec.userName.userList = $EventUsername
			if ($EventChainId)
				Write-debug "EventChainId was given"
				$EventFilterSpec.EventChainId = $EventChainId
			if ($EntityName)
				Write-debug "Entity was given"
				$entity = get-view -viewtype $ViewType -Filter @{ 'name' = $EntityName } -Property name
				$EventFilterSpec.Entity = New-Object VMware.Vim.EventFilterSpecByEntity
				$EventFilterSpec.Entity.Entity = $entity.moref
				$EventFilterSpec.Entity.Recursion = $Recursion
			$EventCollector = get-view -id $EM.CreateCollectorForEvents($Eventfilterspec)
			write-debug "Collector rewinded"
			$events = $null
			while ($EventInWindow = $EventCollector.ReadNextEvents(100))
				$Events += $EventInWindow
				write-debug "Reading next window"

Using SearchIndex in PowerCLI , searching vms by their dns name, ip, and more

Today i want to bring closer something that might not be utilized that often.
What is SearchIndex and what can it do for us you might ask ? Well, best description is at the source 😉 so

The SearchIndex service allows a client to efficiently query the inventory for a specific managed entity by attributes such as UUID, IP address, DNS name, or datastore path. Such searches typically return a VirtualMachine or a HostSystem. While searching, only objects for which the user has sufficient privileges are considered. The findByInventoryPath and findChild operations only search on entities for which the user has view privileges; all other SearchIndex find operations only search virtual machines and hosts for which the user has read privileges. If the user does not have sufficient privileges for an object that matches the search criteria, that object is not returned.

After connecting to virtual center using PowerCLI, you want to initialize the SearchIndex first:

We start from getting ServiceInstance, from the content we take view of the SearchIndex

$si = get-view -id ServiceInstance
$SearchIndex = Get-view -id $si.Content.SearchIndex

What can do SearchIdex for us ?

$SearchIndex | gm -MemberType 'Method'

TypeName: VMware.Vim.SearchIndex

Name                Member
----                ------
Equals              Method
FindAllByDnsName    Method
FindAllByIp         Method
FindAllByUuid       Method
FindByDatastorePath Method
FindByDnsName       Method
FindByInventoryPath Method
FindByIp            Method
FindByUuid          Method
FindChild           Method

How to get a VM with dns name of X, well you can filter that vm from the all vms by looking at their properties for example. Another example is to use get-view with filter on that hostname property :

get-view -ViewType virtualmachine -filter @{'Guest.Hostname'='vm01.domain.corp'}

And now we are going to utilize SearchIndex to do the same:

Type		Value
----		-----
VirtualMachine	vm-8254

In return we have received ManagedObjectReference to a virtualmachine. If we want to see it , we would have to get its view.

get-view -id $SearchIndex.FindAllByDnsName($null,'vm98.domain.corp',$true)

The FindAllByDnsName has 3 arguments, the middle one is obviously the queried dns name. First one is for specifying the datacenter in which you want to look for it. The third, is for choosing the type, when it is set to $true, then we will be looking for a vm with that name, if $false, then we will be looking for a vmhost with that name.
For example if looking up host for specific name:

get-view -id $SearchIndex.FindAllByDnsName($null,'esxi01.domain.corp',$false)  

For the datacenter argument , what is expected is a ManagedObjectReference to a particular datacenter. First we need to get the moref for example of our datacenter:

(get-view -ViewType datacenter -Filter @{'name'='OurDC'}).MoRef

And use it with the SearchIndex FindAllByDnsName method

get-view -id $SearchIndex.FindAllByDnsName((get-view -ViewType datacenter -Filter @{'name'='OurDC'}).MoRef,'ourVM01.domain.corp',$true)

Let’s move forward,

We can use Get-View with proper filter like :

get-view -ViewType VirtualMachine -Filter @{'Guest.IpAddress'=''}

or utilize SearchIndex for that



VMware.Vim.ManagedObjectReference[] FindAllByIp(
VMware.Vim.ManagedObjectReference datacenter, 
string ip, 
bool vmSearch

First and thrid argument usage is the same as in previous exmaple.


VMware.Vim.ManagedObjectReference FindByUuid(
VMware.Vim.ManagedObjectReference datacenter, 
string uuid, 
bool vmSearch, 
System.Nullable[bool] instanceUuid

For vm searches we set the vmSearch to true, then if instanceUuid is set to true we can search for using its instanceUuid instead of bios uuid. for example:

-using VC InstanceUuid
-using SMbios Uuid



VMware.Vim.ManagedObjectReference FindByInventoryPath(string inventoryPath)





VMware.Vim.ManagedObjectReference FindByDatastorePath(VMware.Vim.ManagedObjectReference datacenter, 
string path


$SearchIndex.FindByDatastorePath((get-view -ViewType datacenter -Filter @{'name'='FirstFloorDatacenter'}).MoRef,'[DS09_FastDatastore] VMxyz/VMxyz.vmx')



VMware.Vim.ManagedObjectReference FindChild(
VMware.Vim.ManagedObjectReference entity, 
string name


$cluster = (Get-View -ViewType ClusterComputeResource -Filter @{'name'='ClusterA'}).moref
-finds hostA in ClusterA

Find CPU hogging vms using PowerCLI

this time i would like to show how can we check if we have any vms that are hogging cpu for too long. I bet you are already preventing this using VC alarms. So lets build a simple script that helps us out in getting list of vms that have cpu usage at near 100% for some time.
What we have to do here is:
1) figure out where alarms are triggered , for which vms
2) figure out how to get the root folder of alarms
3) figure out how to get definitions of alarms
4) figure out how to select vms that are using cpu too much for some predefined period of time
5) figure out how to get the cpu stats for vms from point number 4

Let’s go:
Lets first get the service instance object:

$si=get-view serviceinstance

I have decided to put more explanations in this post.
So, serviceinstance, what is that ? I think that at best it is described in the documentation. “The ServiceInstance managed object is the singleton root object of the inventory on both vCenter servers and servers running on standalone host agents. The server creates the ServiceInstance automatically, and also automatically creates the various manager entities that provide services in the virtual environment. Some examples of manager entities are LicenseManager, PerformanceManager, and ViewManager. You can access the manager entities through the content property.”
Make sure to use that link to read service instance description, it will really help to understand how it works.
We will be using alarm manager in order to achieve our goal, let’s have a look how we get there.
And ? What to do now ? We see Alarm-AlarmManager. If we would like to return it, we will just get something with Type,Value properties. So how this can help us?
Let’s see what is this by checking the type, and then use get-help on get-view parameter called ID. This should give us some hint what to do next. So This magic Alarm-AlarmManager is actually a moref/ManagedObjectReference , having that we can get its view using get-view.

Then define from when we should build the statistics for vm cpu hogging


Let’s get the VC root folder , and then find out which alarms are triggered there on.

$rootfolderviewalarms=(get-view -id $si.Content.RootFolder).TriggeredAlarmState

Then let’s get the alaram manager object:

$am=get-view -id $si.Content.AlarmManager

Let’s get defined alarms ids in our root vc folder.
We can do this for example using GetAlarm method from our AlarmManager. But..but..but.. how ?! Ok, lets take few steps back. What if we do not know how to do this, or if there even is a method that can do this ? First thing we can do is to inspect the alarm manager, to see what he can do for us.
On the screenshot below, you can see our alarm manager object $am. We want to see what it can do for us, we use get-member to get list of his methods. From there we can see that he has a method called GetAlarm. In order to check what it does we can use the documentation.
From the output of this method, we know that it will be returning morefs(defined alarm ids on particular entity), and in order to use it we need to give it a entity moref, a place where we look for alarms. Now the documentation for GetAlarm method also states that if the entity will not be set, then it will return all visible alarms. If you would like to use it like that, you would have to run it with $null as argument.
In this example we will get only alarms defined on the root of our Virtual Center server.


Once again, what is it that was returned ? Morefs ! correct. As such they don’t hold too much information. We can get that information though. Using what ? Get-View , connected to that id. Screenshot below shows how to get from ids to actual alarm definition objects with information.
Lets take information about those alarms.

$alarmdefinitions=get-view -id $alarmids

Let’s find the alarm id that describes the alarm for virtual machine cpu usage.
Now this part is bit tricky. I am making assumption here that we have only 1 alarm defined for vm cpu usage, and that it was defined in the root virtual center folder. This script will not work if you have defined more alarms than 1 for vm cpu usage because i am searching only for alarm system name ‘alarm.VmCPUUsageAlarm’, and i am not filtering by its name. So we are looking at $alarmdefinitions array that holds definitions of alarms with .info object that has a systemname property. We filter it so we can get in result the VM cpu usage alarm, and selecting its alarm moref.

$vmcpuusagealarmid=($alarmdefinitions|Where-Object {$_.Info.Systemname -eq 'alarm.VmCPUUsageAlarm' }).info.alarm
Type                                              Value
----                                              -----
Alarm                                             alarm-6

So the alarm id that is about vm cpu usage is Alarm-alarm-6.
Let’s get now ids of virtual machines that have currently triggered alarm that we have found previously. Our root VC container had a property called TriggeredAlarmState that holds morefs of entities and alarm ids triggered on those entities. We will now filter them them to get only those that have vm cpu usage alarm triggered.

$vmswithcpualarms=$rootfolderviewalarms|?{$_.Alarm -eq $vmcpuusagealarmid}

So now we have in $vmswithcpualarms only those triggered alarm states that match our vms with alarm of vm cpu usage.
Let’s change ids to vm view objects, so that we can grab vm names. So far we have only in $vmsswithcpualarms properties called Entity which is only a moref.

$cpuhoggingVMs=get-view -property name -id ($vmswithcpualarms | %{$_.Entity})

Now let’s build statistics from a ‘cpu.usage.average’ metric. We will use 2h intervals and we would like to get data from -7 days until now as stated in $days variable. PowerCLI gives us get-stat cmdlet that we will use. It accepts entity names. I am using $cpuhoggingVMS|%{$} in order to return only names directly. Same as if you would type : -Entity ‘vm1′,’vm2′,’vm3′,’vm4’

$result=Get-Stat -Entity ($cpuhoggingVMS|%{$}) -Start (Get-Date).AddDays($days) -Finish (get-date) -Stat 'cpu.usage.average' -IntervalMins 120

We have now our data stored in $result variable, we have a lot of data there, for each virtual machine statistics about its cpu usage.
Ok what if you say that you can not distinguish from which vm is that statistic data ? I say : “We need to go deeper” 🙂
So gm or get-member on the result entry shows that there are more properties than only those which are displayed.


And the last line! We will group statistics for the vms by their name, and then for each of them we will measure their average cpu usage during that period of time.

$reportVMcpu=$result | select value,Entity | Group-Object -Property entity | % {$temp=$_; $ | Measure-Object -Property value -average | select @{n='CPU % Average usage';e={[math]::round($_.average,3)}}, @{n='entity';e={$} }} | Sort-Object -Propert 'CPU % Average usage' -Descending

Now, if we will display our report, we will get a summary of vms and its corresponding average cpu usage through last 7 days in our example.
We can now tell that some vms here have an average of cpu usage for lat 7 days at 99%, that would indicate that something went bad inside this vm, and we need to investigate it. We do not like vms that hog cpus without any reason for too long 😉
Why would we want this report ?
Ok, i bet you are using alarms for VM cpu usage, and the alarm kicks in after 5..15..30.. minutes for example. You might assume that something went wrong inside the vm, but there are vms that for example are working really hard only during some specific time window. For example systems that are doing calculations at end of the month, or that use cpu only for few days in week/month as per design/function. Each time that alarms is triggered you would have to go to vm performance, and check if this is abnormal situation/call the vm owner/ or look for any pattern in its cpu usage. If you will see that this vm behaves as expected because it is normal to consume that amount of cpu only on Mondays, you would ignore that alarm and just wait to see if alarm gets cleared as previously.

I hope that this post will help you start using alarm manager and other managers, as well as understand morefs and using get-view.

Below is the code without any comments.

$si=get-view serviceinstance
$rootfolderviewalarms=(get-view -id $si.Content.RootFolder).TriggeredAlarmState
$am=get-view -id $si.Content.AlarmManager
$alarmdefinitions=get-view -id $alarmids
$vmcpuusagealarmid=($alarmdefinitions|Where-Object {$_.Info.Systemname -eq 'alarm.VmCPUUsageAlarm' }).info.alarm
$vmswithcpualarms=$rootfolderviewalarms|?{$_.Alarm -eq $vmcpuusagealarmid}
$cpuhoggingVMs=get-view -property name -id ($vmswithcpualarms | %{$_.Entity})
$result=Get-Stat -Entity ($cpuhoggingVMS|%{$}) -Start (Get-Date).AddDays($days) -Finish (get-date) -Stat 'cpu.usage.average' -IntervalMins 120
$reportVMcpu=$result | select value,Entity | Group-Object -Property entity | % {$temp=$_; $ | Measure-Object -Property value -average | select @{n='CPU % Average usage';e={[math]::round($_.average,3)}}, @{n='entity';e={$} }} | Sort-Object -Propert 'CPU % Average usage' -Descending


Get-VMHostTimeReport Reporting time from vmhost system

I wanted to check if all of my vmhost system are keeping time with ntp. I wrote recently how to query time from vmhost system using esxcli. Today i want to show how to do this without esxcli, and also produce nice report and a summary which will help investigate issue with host time. I am comparing host time with local time o/s that is converted to UTC. If you are not sure whether your time is accurate then it might be a problem. Solution for this is to query remote utc time. In internet you can find sites that offer time web services that can be easily integrated to this script.
Have in mind that property DiffToUTC is in seconds.
I have tried to optimize this report as much as i can. It was possible to execute this report in 1 minute and 8 seconds. But it was not that readable and did not contain all of this information. On 100 vmhost+ it should fit in 1 – 2 minutes. Before i had approach with obtaining time using esxcli, but that was slower then this approach.
If you know how to query it faster, post a comment. Have in mind that this function is not perfect. I believe that there are better ways to show weather vmhost system is out of time or not. Anyway, this function helps a lot in diagnosing problems time on esx/esxi host systems.
It will state if ntpd is running or not, or for example if you have >100 host you can spot a pattern for ntp servers. Sometimes it is easy to overlook something, for example ntp servers:
Where you can easily see that you had a typo.
Sometimes you are just not aware that ntp service is running.
Or sometimes… 😉
Few screenshots from running this function:
From this screenshot where the report was stored in $myreport, we can see that we have some issues with host time, as there is a difference of 76 second compared to my local os time.
If you see DiffToUTC like 0.0xxxxx that would mean that you are ok. If you get readings > 1 seconds that could indicate something is wrong.
We can also do report for a single vmhost system.
We can do a full report and using the -summary switch, make function to return some description about the report.
Documentation for
HostDateTimeSystem -> Managed Object – HostDateTimeSystem
HostServiceSystem -> Managed Object – HostServiceSystem
I have added now option to check your local time which will be converted to UTC and compare it to UTC time taken from internet. Internet connection should be in place in order to use it. That was added if you suspect that your local time might not be correct and you would like to check it with other source. Please also read disclaimer,usage restrictions before using this time web service. So if you spot that your time differs to much from time taken from that ‘internet returned time’, it might indicate some issues, maybe the web service has issues, or our system.
Function below:

function Get-VMHostTimeReport {
		Gets time from VM Hosts and checks with local time(to utc).

		This function might help investigating issues with vm host time. If it is running without any
		parameter it checks time for all hosts registered in virtual center to which user is currently
		connected. Using parameter SingleVMHost will produce report for single vm host system.
		VMHost should be the name of the host, string.
		Report returns colums : Name (vmhost system name), VMHostTime (Time from vmhost),
		UTCTime (this is the utc time from our local os), NTPServers ( if any are in the vmhost
		configuration), NTPServiceRunning (checks if the ntp service is running on the vmhost),
		DiffToUTC (that's the difference in seconds between time reported by vmhost and our os)
		By default it sorts report by from lowest to highest time difference reported.

		Specify single vmhost name that is registered in VC. This should be a string.
	.PARAMETER  Summary
		Indicate if you would like to receive short summary about produced report.

	.PARAMETER  CheckTimeFromInternet
		Indicate if you would like to see in summary information about your local time and remote 
		time. Time from remote web service will be checked and comapred to your system utc time.

		PS C:\> Get-VMHostTimeReport
		Will produce report for all vmhosts that are registered within VirtualCenter to which user
		is currently connected. It is possible to close the report into a variable for example:
		You can then export this report to csv if needed for example, or view it again :
		$timereport | format-table -autosize
		For viewing convenience
		PS C:\> Get-VMHostTimeReport -SingleVMHost 'myesxhost.local.lan'
		Will produce report for given vmhost that is registered within VirtualCenter to which user
		is currently connected.

		PS C:\> Get-VMHostTimeReport -Summary
		Will produce report . and show a small summary which might indicate if there is a problem
		with time sync on vmhost systems. Example of the summary below:
		UTC time from the current system :Min and Max times during reporting period
		Min: 9/3/2013 4:17:38 PM
		Max: 9/3/2013 4:19:20 PM
		While function was creating this report, first date that was returned by local os was the Min
		and the last date that was returned by local os was the Max value.
		VMHosts reported Times :Min and Max date / time while creating report
		Min: 9/3/2013 4:16:35 PM
		Max: 9/3/2013 4:19:20 PM
		Our vmhost systems reported their date/time. If this time span is too big, this might indicate 
		issues with vmhost ntp sync.
		Time Difference between VMHost and UTC from local os time Min, Max, Avg
		Min: 0.03075
		Max: 76.20985
		Avg: 1.36604993421053
		This is summary for comparing UTC vm host time to UTC time from local os. If you see 
		big Max value >1/2 sec that it might indicate that there is an issue with vmhost ntp time sync
		If a switch parameter CheckTimeFromInternet is present in the summary section there will
		be small report generated about your local time converted to UTC and time taken from
		You can then quickly see if there is an issue with your local time

		NAME:  Get-VMHostTimeReport
		AUTHOR: Grzegorz Kulikowski
		NOT WORKING ? #powercli @ 



if ($SingleVMHost) { $VMHosts=Get-View -ViewType HostSystem -Filter @{'name'=$SingleVMHost} }
$VMHosts=get-view -viewtype hostsystem -property name,ConfigManager.DateTimeSystem,ConfigManager.ServiceSystem -Filter @{'runtime.ConnectionState'='connected'}
Foreach($VMHost in $VMHosts){
$VMHostDateTimeSystem=get-view -id $VMHost.ConfigManager.DateTimeSystem
$VMHostServiceSystem=get-view -id $VMHost.ConfigManager.ServiceSystem
$NtpServiceState=($VMHostServiceSystem.ServiceInfo.Service|Where-Object {$_.Key -eq 'ntpd'}).Running
$TimeReport+=$vmhost| Select-Object -Property Name, @{n='VMHostTime';e={$VMHostTime}},@{n='UTCTime';e={$UTCTime}},@{n='NTPServers';e={$NtpServers}},@{n='NTPServiceRunning';e={$NtpServiceState}},@{n='DiffToUTC';e={[Math]::Round([math]::abs(($VMHostTime - $UTCTime).TotalSeconds),5)}}
$SummaryUTCTime=$TimeReport|Measure-Object -Property UTCTime -Min -Max
$SummaryVMHostTime=$TimeReport|Measure-Object -Property VMHostTime -Min -Max
$SummaryDiffToUTC=$TimeReport|Measure-Object -Property DiffToUTC -Min -Max -Average
Write-Host "UTC time from the current system :Min and Max date/time while creating this report."
Write-Host "Min: $($SummaryUTCTime.Minimum.ToString())"
Write-Host "Max: $($SummaryUTCTime.Maximum.ToString())"
Write-Host "VMHosts reported Times :Min and Max date/time while creating this report"
Write-Host "Min: $($SummaryVMHostTime.Minimum.ToString())"
Write-Host "Max: $($SummaryVMHostTime.Maximum.ToString())"
Write-Host "Time Difference between VMHost and UTC from local os time Min, Max, Avg"
Write-Host "Min: $($SummaryDiffToUTC.Minimum.ToString())"
Write-Host "Max: $($SummaryDiffToUTC.Maximum.ToString())"
Write-Host "Avg: $($SummaryDiffToUTC.Average.ToString())"
[datetime]$TimeFromInternet=(Invoke-RestMethod -Uri '').timezone.utctime
Write-Host "We took UTC time from internet and compared it to your local time converted to UTC time"
Write-Host "Reported local time converted to UTC $CurrentSystemTimeUTC"
Write-Host "Reported time taken from internet( $TimeFromInternet"
Write-Host "Difference: $TimeDiff seconds"
return $TimeReport | Sort-Object -Property DiffToUTC

Issues with vmmonitoring in HA clusters while using vsphere client 5.0.0 build 455964, vm monitoring with vmware tools down will not restart failed vm

I wanted to share with everybody this ‘news’.

While trying to create vm monitoring within HA cluster using vm monitoring only i went into some issues. VM monitoring was not working. I thought there is not that much to configure to have this working right ? Open cluster settings, go to vm monitoring section

Continue reading

get-vievent too slow ? :) BOOSTING get-vievent !

There was quite interesting question on communities today. I think it’s worth to share it with everybody what and how 😉
Right so, let’s say you want to get some events from entities using get-vievent:

Retrieves information about the events on a vSphere server. An event is any action in the vCenter Server system or ESX host. The cmdlet collects events that correspo
ned by the cmdlet parameters. Filters are additive and the Entity. Start, and Finish parameters filter the events both by the entity and the timestamp properties. To
om the default one, use the -Server parameter.

Continue reading