PoshCode Archive  Artifact [8b4be57e73]

Artifact 8b4be57e737123030187d92e19be14614813e541e6c3d89df0f273065e31778e:

  • File cpu-usage.ps1 — part of check-in [5eca885104] at 2018-06-10 13:58:31 on branch trunk — this function calculates cpu usage through wmi object (user: unknown size: 1993)

# encoding: ascii
# api: powershell
# title: 
# description: this function calculates cpu usage through wmi object
# version: 0.1
# type: function
# license: CC0
# function: cpu-usage
# x-poshcode-id: 565
# x-archived: 2008-09-15T21:29:49
#
#
function cpu-usage
 { if ($Args)
        {$machine=$Args}
    else
        {$machine="localhost"}
      
#loop to refresh information cpu usage            
 while($auxiliary -ne 'Q')
       {

#first sample of processes
$before   = gwmi win32_perfrawdata_perfproc_process -ComputerName $machine
sleep -Milliseconds (100) 

#second sample of processes
$after = gwmi win32_perfrawdata_perfproc_process -ComputerName $machine

#hash list with the difference of two samples
$difference = @{}
#array with cpu percentage for each process
$result = @{}


#compare two samples and store difference in $difference["processname"]
foreach ($process_before in $before)
{ foreach ($process_after in $after)
    { if ($process_after.name -eq $process_before.name)
        {$difference_process = [long]$process_after.percentprocessortime -[long]$process_before.percentprocessortime
         $difference[$process_before.name] = $difference_process      
        }
    }
}

#total cpu time
$sum = $difference["_Total"]

#with all processes, we calculate percentaje
foreach ($i in $difference.keys)
    {$result[$i] = ((($difference.$i)/$sum)*100)
    }

          
#sort array descending
$result= (($result.GetEnumerator() | sort value -Descending)[1..10])

  
      Clear-Host
      Write-Host ""
      Write-Host "press Q to quit, another key to refresh"
    
     format-table -AutoSize -InputObject $result @{Label= "Name:"; Expression = {$_.name}},`
        @{Label = "percentaje CPU"; Expression= {"{0:n2}" -f ($_.Value)}}
      
        $auxiliary = $Host.UI.RawUI.ReadKey()
        $auxiliary = [string]$auxiliary.character
        $auxiliary=$auxiliary.toupper()       
        }      
}