Home > event, PowerCLI, PowerShell, Session Manager > Get complete vCenter session info

Get complete vCenter session info

January 17th, 2012 Leave a comment Go to comments

There was an interesting thread in the PowerCLI Community today. It raised the question how one could report on the current vCenter sessions, including the IP address or hostname from where the session was started.

Unfortunately the SessionManager doesn’t hold any information from where the session was started.

But there are other ways of finding that information. The UserLoginSessionEvent object has a property, called ipAddress, that has the information we’re after.

Btw if you are only interested in looking for idle sessions, independent from which host they were started, there is a great post, called List and Disconnect vCenter Sessions on the PowerCLI blog.

Update May 4th 2012: function updated to handle multiple vCenter connections.

The script

function Get-VISessionInfo{
<#
.SYNOPSIS  Retrieve vCenter session information
.DESCRIPTION The function will retrieve the open vCenter
  session, including the IP address and hostname from where
  the session was started
.NOTES  Author:  Luc Dekens
.PARAMETER AllowedDifference
  The timestamps from the Session Manager entries and the
  event objects can sometimes differ, depending on the vCenter
  activity. The default is 1 second, but this can be changed
  with this parameter. The unit for this parameter is seconds.
.EXAMPLE
  PS> Get-VISessionInfo
#>

  param(
  [CmdletBinding()]
  [int]$AllowedDifference = 1
  )

  process{
    if((Get-PowerCLIConfiguration).DefaultVIServerMode -eq "Multiple"){
      $vcenter = $defaultVIServers
    }
    else{
      $vcenter = $defaultVIServers[0]
    }

    foreach($vc in $vcenter){
      $sessMgr = Get-View SessionManager -Server $vc
      $oldest = ($sessMgr.SessionList | Sort-Object -Property LoginTime | Select -First 1).LoginTime
      $users = $sessMgr.SessionList | %{$_.UserName}
      $events = Get-VIEvent -MaxSamples ([int]::MaxValue) -Start $oldest.AddHours(-1) -Server $vc |
      where {$_ -is [VMware.Vim.UserLoginSessionEvent] -and $users -contains $_.UserName} |
      Sort-Object -Property CreatedTime

      $allowedDiffTS = New-TimeSpan -Seconds $AllowedDifference

      foreach($session in $sessMgr.SessionList){
        $events |
        where {[math]::Abs(($session.LoginTime.ToLocalTime() - $_.CreatedTime).Ticks) -lt $allowedDiffTS.Ticks -and
          $users -contains $_.UserName} | %{
          New-Object PSObject -Property @{
            vCenter = $vc.Name
            "Session login" = $session.LoginTime
            UserName = $_.UserName
            IPAddress = $_.IPAddress
            Hostname = [System.Net.Dns]::GetHostEntry($_.IPAddress).HostName
          }
        }
      }
    }
  }
}

Annotations

Line 23-28: If the PowerCLI session is configured in “Multiple” mode, the function will loop through all connected vCenters. The Get-PowerCLIConfiguration cmdlet is used to retrieve the active mode.

Line 32: The script will look for the session with the oldest login time. This will allow us to limit the number of events that need to be retrieved.

Line 33: Besides the timestamps, the script will also check if the username that appears in an user session login event, is one of the users that has an open vCenter session.

Line 34-36: We retrieve the UserLoginSessionEvent for users that have an open vCenter session.

Line 38: The time difference we allow between the timestamp in the session and the corresponding UserLoginSessionEvent is converted to a TimeSpan object.

Line 42: To link a vCenter session to a UserLoginSessionEvent the script calculates the time difference between the timestamps in the UserLoginSessionEvent and the session object from the SessionManager. If the absolute time difference falls below the accepted time difference ($AllowedDifference), the event is linked to the session.

Line 44-49: The result is placed in the pipeline

Line 45: The output contains the name of the vCenter where the session was found.

Line 49: The script converts the IP address to the hostname with the GetHostEntry method.

Sample usage

The function is rather simple in use.


Get-VISessionInfo

And the result looks something like this.

Enjoy!

  1. amit
    May 1st, 2013 at 15:19 | #1

    how i create VISessionInfo olease to view ip and hostname?

  2. Paul Anderson
    May 24th, 2012 at 17:05 | #2

    I’m getting similar errors to Wayne:

    You cannot call a method on a null-valued expression.
    At H:\Scripts\VMware PowerCLI\Get-VISessionInfo.ps1:34 char:82
    + $events = Get-VIEvent -MaxSamples ([int]::MaxValue) -Start $oldest.AddHours <<<< (-1) -Server $vc |
    + CategoryInfo : InvalidOperation: (AddHours:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At H:\Scripts\VMware PowerCLI\Get-VISessionInfo.ps1:42 char:59
    + where {[math]::Abs(($session.LoginTime.ToLocalTime <<<< () – $_.CreatedTime).Ticks) -lt $allowedDiffTS.Ticks -and
    + CategoryInfo : InvalidOperation: (ToLocalTime:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    I don't know why $oldest and $session.LoginTime are NULL. LucD, can you please help ?

    PS: If this is a duplicate post, sorry, my last post appeared to fail.

  3. Pedro Magalhaes
    May 4th, 2012 at 12:50 | #3

    Please check if you are connected to more than one vcenter server

    • May 4th, 2012 at 17:31 | #4

      @Pedro, I have updated the function to handle multiple vCenter connections.

  4. chris
    March 14th, 2012 at 16:04 | #5

    45 lines of code to get an IP address – really? This looks like a great script but having to write 45 lines of code to get to this tells me something was left out in the design process.

    • March 14th, 2012 at 17:35 | #6

      Hi Chris, there are 14 lines of comments in there as well.
      But seriously, I agree with you, the script uses another source (Events) to find the IP addresses which should have been there in the first place.
      There is definitely room for improvement :-)

  5. Tom
    March 13th, 2012 at 07:36 | #7

    @Wayne
    I got the same message when I tried running it, anyone have any hot tips as to what I am doing wrong?

  6. Wayne
    February 8th, 2012 at 22:45 | #8

    Tried running the script I received a couple of errors….

    You cannot call a method on a null-valued expression.
    At P:\Powershell\Vmware\Get-vcenter-sessions\get-VISessionInfo.ps1:26 char:80
    + $events = Get-VIEvent -MaxSamples ([int]::MaxValue) -Start $oldest.AddHours <<<< (-1) |
    + CategoryInfo : InvalidOperation: (AddHours:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    You cannot call a method on a null-valued expression.
    At P:\Powershell\Vmware\Get-vcenter-sessions\get-VISessionInfo.ps1:34 char:57
    + where {[math]::Abs(($session.LoginTime.ToLocalTime <<<< () – $_.CreatedTime).Ticks) -lt $allowedDiffTS.Ticks -and
    + CategoryInfo : InvalidOperation: (ToLocalTime:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

  7. Kyle Hanson
    February 1st, 2012 at 00:33 | #9

    Nice script. :)

    Good to have a script like this ready for troubleshooting connection issues.

  1. No trackbacks yet.