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!

Tagged with:
 

One Response to Finding and Stopping VI Sessions with Powershell

  1. Larry says:

    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.

Leave a Reply