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:

1. Find scripts that lack the Disconnect-VIServer command:

$Path = “D:\Scripts”
$ConnectMatches = Get-ChildItem $Path -Recurse |
   Where {$_.PSIsContainer -eq $False} |
   Select-String “Connect-VIServer” |
   Where {$_.Line -notmatch “Disconnect”}
$DisconnectMatches = Get-ChildItem $Path -Recurse |
   Where {$_.PSIsContainer -eq $False} |
   Select-String “Disconnect-VIServer”
Compare-Object -ReferenceObject $ConnectMatches`
  -DifferenceObject $DisconnectMatches -Property Path

2. Disconnect old sessions through the VI Client GUI

On the Administration page of the VI Client, click on the Sessions tab. Sort by Status, Select the sessions that have been idle for a long time and click Terminate.

3. Use a script to disconnect old sessions

That’s more like it! Now who would want to go clicking and sorting about in the VI Client? ;) Thank goodness we have the VI Toolkit. Here’s the code:

$VCServerName = “YourVCServerName”
$HoursOld = 24        # 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
Write-Host “The VI Toolkit ROCKS!”

Enjoy!

»crosslinked«

4 thoughts on “To Disconnect(-VIServer) or not to Disconnect”

  1. Pingback: VMware: Disconnect idling vCenter sessions with PowerCLI

Leave a Reply