dewyser.net

solutions, scripting and more

Querying Horizon Server API — 6th Aug 2024

Querying Horizon Server API

I recently was asked, how can we get a list of all the devices connecting to our environment and what client are they using to do so? With the help of the VMware.Hv.Helper I came up with the following in a couple of minutes:

function Get-ViewAPIService {
  param(
    [Parameter(Mandatory = $false)]
    $HvServer
  )
  if ($null -ne $hvServer) {
    if ($hvServer.IsConnected) {
      return $hvServer.ExtensionData
    }
  }
}

function Get-HVGlobalSession { 
  param(
    [Parameter(Mandatory = $false)]
    $HvServer = $null
  )
    
  $services = Get-ViewAPIService -HvServer $HvServer
  
  $query_service_helper = New-Object VMware.Hv.GlobalSessionQueryServiceService
  $query = new-object vmware.hv.GlobalSessionQueryServiceQuerySpec
    
  $SessionList = @()
  foreach ($pod in $services.Pod.Pod_List()) {
    $query.pod = $pod.id
    $queryResults = $query_service_helper.GlobalSessionQueryService_QueryWithSpec($services, $query)
    $GetNext = $false
    do {
      if ($GetNext) { 
        $queryResults = $query_service_helper.GlobalSessionQueryService_GetNext($services, $queryResults.id)
      }
      $SessionList += $queryResults.results
      $GetNext = $true
    } while ($queryResults.remainingCount -gt 0)
    $query_service_helper.GlobalSessionQueryService_Delete($services, $queryresults.id)
  }
  return $sessionlist
}

function Connect-HV() {
  param (
    [string] $HvServer,
    [string] $username,
    [securestring] $password,
    [string] $domain
  )

  $connection = Connect-HVServer -Server $HvServer -User $username -Password $password -Domain $domain -ErrorAction Stop

  return $connection
}

function Disconnect-HV() {
  param (
    [string] $HvServer
  )

  Disconnect-HVServer -Server $HvServer -ErrorAction Stop -Confirm:$false
}


$target_connection_server = "<connection server>"
$service_account_username = "<username>"
$service_account_domainname = "<domain>"
$service_account_password = ConvertTo-SecureString -AsPlainText "<password>" -Force

$connection = Connect-HV -HvServer $target_connection_server -username $service_account_username -password $service_account_password -domain $service_account_domainname

$sessions = Get-HVGlobalSession -HvServer $connection

$endpoints = $sessions.namesdata | Select-Object -ExpandProperty BaseNames
$endpoints | Format-Table UserName, ClientName, ClientVersion 

Disconnect-HV -HvServer $target_connection_server