Get vCenter User Sessions and Idle times with PowerCLI

Today I was looking into a small “nice to have” notification system for users that had left their vSphere clients open and logged into vCenter. I found this great bit of script to list currently logged in users over at blog.vmpros.nl and thought I would expand on this in my own way to generate a handy list of logged in users and their current idle time – similar to the way the “Sessions” tab in the vSphere client displays user session information. When I got home this evening I expanded on the original script from vmpros.nl to create the following:

 

$Now = Get-Date
$Report = @()
$svcRef = new-object VMware.Vim.ManagedObjectReference
$svcRef.Type = "ServiceInstance"
$svcRef.Value = "ServiceInstance"
$serviceInstance = get-view $svcRef
$sessMgr = get-view $serviceInstance.Content.sessionManager
foreach ($sess in $sessMgr.SessionList){
   $time = $Now - $sess.LastActiveTime
   # Our time calculation returns a TimeSpan object instead of DateTime, therefore formatting needs to be done as follows:
   $SessionIdleTime = '{0:00}:{1:00}:{2:00}' -f $time.Hours, $time.Minutes, $time.Seconds
   $row = New-Object -Type PSObject -Property @{
   		Name = $sess.UserName
		LoginTime = $sess.LoginTime
		IdleTime = $SessionIdleTime
	} ## end New-Object
	$Report += $row
}
$Report

 

[download id=”6″]

 

Here is an example of the output of the script:

 

Using this bit of PowerCLI script, it should be easy for you to create your own notification system based on user session idle time, or some functionality that would disconnect idle users. Let me know if you do improve on the above, or if you have any other suggestions.

 

6 thoughts on “Get vCenter User Sessions and Idle times with PowerCLI”

  1. Stu :
    It’s helpful to append ‘.ToLocalTime()’ to LoginTime and LastActiveTime.

    Thank You For this Tip!! My time was off eight hours and this fixed it.

  2. Hi Alan,

    Thanks for the feedback – much appreciated. That is a great blog post. I was wondering what kinds of limits were in place for vCenter sessions, as I have always noticed old sessions left over in the environment I work with from PowerCLI scripts! I’ll definitely be looking into using Disconnect-ViSession for these stale/idle sessions going foward – I was already thinking that I didn’t like the fact I was leaving old PowerCLI vCenter sessions over from all my scripts 🙂 Thanks!

    Sean

Leave a Comment