Powershell – List all vCenter client sessions & disconnect if inactive

By | March 10, 2010

Today I needed to create a list of all users connected to a vCenter sever through the Client.
And during so I created a few variants 🙂

This creates a list of all usernames connected to the vCenter server through a vCenter Client.

$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){
   write "$($sess.UserName)"
}

If you want to see a witch clients have been idle for 60 minutes try this.

$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){
    if (($sess.LastActiveTime).addminutes(60) -lt (Get-Date)){
        write "$($sess.UserName)"
      }
}

If you the want to terminate the sessions that have been inactive  for more than 60 minute

$svcRef = new-object VMware.Vim.ManagedObjectReference
$svcRef.Type = "ServiceInstance"
$svcRef.Value = "ServiceInstance"
$serviceInstance = get-view $svcRef
$sessMgr = get-view $serviceInstance.Content.sessionManager
$oldSessions = @()
foreach ($sess in $sessMgr.SessionList){
    if (($sess.LastActiveTime).addminutes(60) -lt (Get-Date)){
        $oldSessions += $sess.Key
      }
}
$sessMgr.TerminateSession($oldSessions)

You can modify the hell out of this script to suit your needs and be my guest….

You can download the full script here.

The scripts are based on code found  at the PowerCLI community by LucD.
http://communities.vmware.com/message/914858#914858

9 thoughts on “Powershell – List all vCenter client sessions & disconnect if inactive

  1. Cyril

    Hi,

    I get the following error when running your script and I cannot figure out why:

    Exception calling “TerminateSession” with “1” argument(s): “The object or item referred to could not be found.”
    At line:1 char:26
    + $sessMgr.TerminateSession <<<< ($oldSessions)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    VMware vSphere PowerCLI 4.0 U1 build 208462

  2. Pingback: VMware: Disconnect idling vCenter sessions with PowerCLI | VMpros.nl

  3. Pingback: VMware: Disconnect idling vCenter sessions with PowerCLI

  4. Matt Boren

    Good stuff, thanks for sharing. Wanted to share a tidbit about this: While the first five (5) lines are a way to get the .Net View object of the SessionManager, you can also get that same View object via:

    $sessMgr = Get-View ‘SessionManager’

    80% reduction in code: I’ll take it!

Leave a Reply

Your email address will not be published. Required fields are marked *