VMware Cloud Community
Meteor_Diva
Contributor
Contributor

Get host cpu core usage and export to csv

Hi everyone, I am new to PowerShell and PowerCLI,

I want to create a script that shows all the CPU core usage, and I write something like this :

 

    $cpuUsage = get-vmhost -Name 192.168.1.82 | get-stat -stat 'cpu.usage.average' -Realtime |
    Group-Object -Property Instance | Where-Object -Property Name -NE "" | Sort-Object -Property Name
    for ($i = 0; $i -lt $cpuUsage.Length; $i++) {
        $cpuUsage | Where-Object -Property Name -eq $i |
        Select-Object -ExpandProperty Group | Select-Object Timestamp, @{ Name = "instance$i";Expression ={$_.Value}} | 
        Export-Csv -Path test.csv -Append -Force
    } 

 

 

The results I want are something like this :

Timestampinstance0instance1 instance2 instance3instance4instacne5
22/4/202214:13:40
1.232.14.31.71.651.32
22/4/202214:13:20
1.762.52.13.11.11.21
22/4/202214:13:00
1.562.51.32.051.21.5

 

But the output of my script was like this :

Timestampinstance0
22/4/202214:13:401.23
22/4/202214:13:201.76
22/4/202214:13:001.56
22/4/202214:13:40 
22/4/202214:13:20 
22/4/202214:13:00 
22/4/202214:13:40 
22/4/202214:13:20 
22/4/202214:13:00 
22/4/202214:13:40 
22/4/202214:13:20 
22/4/202214:13:00 
22/4/202214:13:40 
22/4/202214:13:20 
22/4/202214:13:00 
22/4/202214:13:40 
22/4/202214:13:20 
22/4/202214:13:00 

 

I will be grateful if somebody can help me to improve this script.

0 Kudos
1 Reply
LucD
Leadership
Leadership

You could do something like this

 

$esxName = '192.168.1.82'

$esx = Get-VMHost -Name $esxName
$instances = 0..($esx.ExtensionData.Hardware.CpuInfo.NumCpuThreads - 1)

Get-Stat -Entity $esx -Stat 'cpu.usage.average' -Instance $instances -Realtime |
Group-Object -Property TimeStamp -PipelineVariable group |
ForEach-Object -Process {
  $obj = [ordered]@{
    VMHost = $esx.Name
    TimeStamp = $group.Name
  }
  $group.Group | Sort-Object -Property {[int]$_.Instance} |
  ForEach-Object -Process {
    $obj.Add("Instance$($_.Instance)",$_.Value)
  }
  New-Object -TypeName PSObject -Property $obj
} | Export-Csv -Path test.csv -Append -UseCulture -Force

 


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference