VMware: Disconnect idling vCenter sessions with PowerCLI

8

Today I was browsing my vCenter server and saw multiple vCenter idle sessions connected to the vCenter server. I was thinking.. there must be a PowerCLI script made by a CLI freak that will disconnect my old sessions.. and there is 🙂

 image

With this Powershell script you get an outputh of the connected vCenter users:

$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)"}
}

 

image

^ Credits and thanks for this script goto Anders Mikkelsen

To disconnect the idling sessions (12h +) you can run the following script:

  

$VCServerName = “YourVCServerName”
$HoursOld = 12        # Modify value at your pleasure
$VC = Connect-VIServer $VCServerName
$ServiceInstance = Get-View ServiceInstance
$SessionManager = Get-View $ServiceInstance.Content.SessionManager
$SessionManager.SessionList |
   Where {$_.LastActiveTime -lt (Get-Date).AddHours(-$HoursOld)} |
   % {$SessionManager.TerminateSession($_.Key)}
Disconnect-VIServer -Confirm:$False

$VCServerName = FQDN

$HoursOld = Max hours to kill the idling sessions ( I prefer 12 hours)

image

^ Credits and thanks for this script goto Hugo Peeters

 

Now my connected sessions are:

image

Time to schedule the disconnect script every day and slap some colleagues to close their sessions 🙂

About Author

8 thoughts on “VMware: Disconnect idling vCenter sessions with PowerCLI

Leave a Reply

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