If you have been trying out the VMware VI Toolkit for Windows Powershell, you have probably noticed. You have to disconnect (disconnect-viserver) each session you set up to the VI Server (connect-viserver), or it will linger for eternity (or until the next reboot at least). That’s why I always include a disconnect-viserver command at the end of my VI Toolkit scripts. But what happens in real life: when debugging a script, it hardly ever reaches the end of the script. It will stop at an error or be cancelled by me to fix some bug I notice. I regularly check the Sessions tab in my VI Client and terminate all my idle sessions to keep VI clean and fast. So why not automate that too? Here’s how:
function Get-Session
{
$Global:SI = Get-View ServiceInstance
$Global:SM = Get-View $SI.Content.SessionManager
Return $SM.SessionList
}function Stop-Session
{
Process
{
ForEach ($Session in $_)
{
If ($Session.Key -ne $SM.CurrentSession.Key)
{
$Key = $session.Key
$SM.TerminateSession($Key)
Write-Host “Session $Key terminated.”
$Key = $null
}
Else
{
Write-Warning “Cannot terminate current session.”
}
}
}
}
The function Get-Session lists the currently active sessions. You can then filter them as you do any collection of objects in Powershell and pipe them to Stop-Session to have them terminated. Note that VI Client sessions appear to create two actual sessions and that the API (and therefore my function) will not allow you to terminate the current session.
Example:
Get-Session | Where { ((Get-Date) – $_.LastActiveTime).TotalHours -ge 8 } | Stop-Session
Enjoy!
One Response to Finding and Stopping VI Sessions with Powershell
Tags
Active Directory API bind order cleanup cluster CPU Custom Fields datastores description device management directory tree errors Event Log file name filter Fun function HA IT known issues License Server LUN multipath NIC objects Oneliner portgroups PowerCLI PowerShell profile recursive Registry Scripts security session share snapshots SQL Stat VI Toolkit VMware vSphere WMI WSUS ZenArchives
- July 2012
- July 2011
- February 2011
- January 2011
- December 2010
- May 2010
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008





Finding and Stopping VI Sessions with Powershell – the line $.LastActiveTime is in GMT while Get-Date returns EDT. I know I can just remove 5 house but do you know how in poweshell to return the values in local time ? Thanks for the scripts.