Finding and Stopping VI Sessions with Powershell

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!

»crosslinked«

To Disconnect(-VIServer) or not to Disconnect

With the release of VI Toolkit v1.0, the bèta-cmdlet Get-VIServer has been renamed to Connect-VIServer, which more accurately describes the action. The opposite action is now also available in the form of Disconnect-VIServer. Every script you start with Connect-VIServer should end with Disconnect-VIServer if you’d like to keep the amount of open sessions to your Virtual Center Server to a minimum. And you do if you like having any sort of performance from your VC Server.

Here’s three ways you can make sure you don’t end up with unnecessary sessions:

Continue reading “To Disconnect(-VIServer) or not to Disconnect”