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
thanks, very helpful scripts
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
Hi,
Just tested the script and it worked fine.
What versions of PowerCLI and PowerShell are you using.
Hi,
I use VMware vSphere PowerCLI 4.0 U1 build 208462
and the Powershell version 2
Pingback: VMware: Disconnect idling vCenter sessions with PowerCLI | VMpros.nl
New Script Works like a charm. Thanks for your help guys.
Pingback: VMware: Disconnect idling vCenter sessions with PowerCLI
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!
Hi Matt,
Thanks for sharing.
It’s always nice to get my code optimized.
A. Mikkelsen