Pages

Total Pageviews

Monday, October 22, 2012

Disconnecting the Idle Sessions in Vsphere Server


Displaying the sessions on a vsphere server . 

Following script  can be used to display the sessions on the vsphere server


Function Get-ViSession { 
    
    $SessionMgr = Get-View $DefaultViserver.ExtensionData.Client.ServiceContent.SessionManager 
    $AllSessions = @() 
    $SessionMgr.SessionList | Foreach {    
        $Session = New-Object -TypeName PSObject -Property @{ 
            Key = $_.Key 
            UserName = $_.UserName 
            FullName = $_.FullName 
            LoginTime = ($_.LoginTime).ToLocalTime() 
            LastActiveTime = ($_.LastActiveTime).ToLocalTime() 
            
        } 
            If ($_.Key -eq $SessionMgr.CurrentSession.Key) { 
                $Session | Add-Member -MemberType NoteProperty -Name Status -Value "Current Session" 
            } Else { 
                $Session | Add-Member -MemberType NoteProperty -Name Status -Value "Idle" 
            } 
            $Session | Add-Member -MemberType NoteProperty -Name IdleMinutes -Value ([Math]::Round(((Get-Date) – ($_.LastActiveTime).ToLocalTime()).TotalMinutes)) 
    $AllSessions += $Session 
    } 
    $AllSessions 
}

Get-ViSession vsphereserver



Disconnecting the sessions which are idle for 30 min 


Connect-VIServer vsphereserver -User username -Password pwd

Function Disconnect-ViSession { 
       [CmdletBinding()] 
    Param ( 
        [Parameter(ValueFromPipeline=$true)] 
        $SessionList 
    ) 
    Process { 
        $SessionMgr = Get-View $DefaultViserver.ExtensionData.Client.ServiceContent.SessionManager 
        $SessionList | Foreach { 
            Write "Disconnecting Session for $($_.Username) which has been active since $($_.LoginTime)" 
            $SessionMgr.TerminateSession($_.Key) 
        } 
    } 
}
Get-VISession | Where { $_.IdleMinutes -gt 30 } | Disconnect-ViSession