Further to an earlier post regarding vROPs collection/monitoring of temperature readings, i would like to share some code to extract that data.

There are different reasons why you may wish to do this such as to import the data into a big data analysis tool. I won’t get into the reasons why but if you (like me) have a need to do such a thing, then here is the code I used to extract that data.

The code and comments are fairly self-explanatory so i will not cover it line by line.

In brief, it will generate a list of every ESX host that vROPs knows about and use that information to iterate through and extract the metric readings for every component temperature sensor available for that physical device.

It will then build a custom object that matches the resourceID to the Hostname along with the metrics collected and export the data into a CSV.

You could obviously approach this in different ways particularly with the output format. I actually had this running on a loop to perform regular exports of the readings.

This code takes some inspiration from the vman. Checkout his post and his other great posts –

http://vman.ch/vrops-suite-api-report-notifications-alarms/.

 

<##############################################################
Script author: James Gill
Date Last Updated: 17/05/2017

INFORMATION  –
– Retrieves a list of every known Host System in vROPs (with associated ResourceID and ResourceName)
–    Creates a resource name lookup table on the fly
–    Retrieves the last known temperature reading
–    Performs a lookup to associate the returned data with a ResourceName (Hostname) based on the ResourceID
–    Converts temperature reading time to human readable format (its in epoc format by default)
–    Writes it to a CSV  ############################################################## #>

$cred = Get-Credential

# Define required headers to supply to the Web request
$headers = @{
    		"Accept" = "application/json"
            "Content-Type" = "application/json"
	        }
	

# The code below will deal platforms using selfsigned certificates and should be removed for Production use cases
add-type @"
     using System.Net;
     using System.Security.Cryptography.X509Certificates;
     public class TrustAllCertsPolicy : ICertificatePolicy 
     {
         public bool CheckValidationResult(
             ServicePoint srvPoint, X509Certificate certificate,
             WebRequest request, int certificateProblem) 
             {
             return true;
         }
     }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

# Set the target vROPs platform e.g. myvropsserver01.mydomain.com
$vRops = 'enter server here' 

Write-Output "Collecting Host System Resources and Temperature Data from $vRops"  

#Retreive host system information to determin volume and deal with page counts to cope with large datasets
$RList = Invoke-RestMethod -Method Get -Uri "https://$vRops/suite-api/api/resources/?pageSize=1&ResourceKind=HostSystem" -Credential $cred

[int]$ResourceCount = $RList.resources.pageInfo.totalCount
write-output "Resource count: $ResourceCount"
    If ($ResourceCount -lt 5001){
 
        $RListCount = 1 }

    Else { 
        
        [int]$RListCount = [math]::Round($ResourceCount/5000) 
    
    }
    Write-Output "Resource page count: $RListCount"

    # Retreive the the list of all host systems with their ResourceID and Resource name
    # Iterate through each page and add the return data to the lookup table
    $resourceIdLookupTable = @{}
    $i=0
            While ($i -ine $RListCount) {

            Write-Output "Retreiving resource data for page $i"            
            $RListURL = 'https://' + $vRops + '/suite-api/api/resources?page=' + $i + '&ResourceKind=HostSystem&pageSize=5000'
            Write-Output "Page $i RListURL: $RListURL"

            $RList = Invoke-RestMethod -Method Get -Uri $RListURL -Credential $cred

                Write-Output "Adding page $i results to ResourceIDLookupTable"
                ForEach ($Item in $Rlist.resources.resource){
                    $resourceIdLookupTable += @{$Item.identifier = $Item.resourceKey.name}
                                       
                   }                              
            $i++
            }


# From the list of all Hosts Systems, iterate through and collect the temperature reading

$ResourceIDList = $RList.resources.resource.identifier
$TemperatureStats = @()

Foreach($HostSystem in $resourceIdList) {

    $CurrentResourceID = $HostSystem

    $RequestedStat =  'Sensor|temperature:|currentValue'

    $StatsURI = 'https://' + $vRops + '/suite-api/api/resources/stats/latest?resourceId=' + $CurrentResourceID + '&statKey=' + $RequestedStat
    Write-Output "$StatsURI"

    $Stats = @()
    $Stats = Invoke-RestMethod -Method get -Uri $StatsURI -Headers $headers -Credential $cred

    # Grab the data we need from the nested objects
    Write-Output "grabbing data from object"

    $DataSet = $Stats.values | select -ExpandProperty Stat-list | select -ExpandProperty stat

    foreach ($item in $DataSet) {

    [Int64]$TimeStamp = ($item | select -ExpandProperty TimeStamps)
    $StatKey = ($item.statKey | select -ExpandProperty key)
    [Int]$Temperature = ($item | select -ExpandProperty Data)

                    # Create the PSObject that contains our formated data
                    $TemperatureStats += New-Object PSObject -Property  @{

                    ResourceName        = $resourceIdLookupTable.Item($CurrentResourceID)
                    ResourceID          = $CurrentResourceID
                    epocTime            = $TimeStamp
                    ConvertedTime       = If ([int64]$TimeStamp -gt '') {([TimeZone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddMilliSeconds([int64]$TimeStamp))).tostring("dd/MM/yyyy HH:mm:ss")} else {}
                    StatKey             = $StatKey
                    "Temperaturec(*c)"  = $temperature
                    }
            }
}

#Set the output location
$ScriptPath = (Get-Item -Path ".\" -Verbose).FullName
$csvReport = "$ScriptPath\vROPsTemperatureReadings.csv"

$TemperatureStats | sort ResourceName | select epocTime, ConvertedTime, ResourceID, ResourceName, StatKey, 'Temperaturec(*c)' | Export-Csv -Path $csvReport -NoTypeInformation

Happy scripting… 🙂