I have a script that works fine on some machines,(all machines have same,5.1 Powershell version)
Script calculates CPU usage percentage for windows services
$cpu = Get-WmiObject –class Win32_processor -Property NumberOfCores, NumberOfLogicalProcessors
# Define the number of top services to display
$services = Get-WmiObject Win32_Service | Where-Object { $_.State -eq 'Running' } | Sort-Object -Property ProcessId | ForEach-Object {
$process = Get-Process -Id $_.ProcessId
if ($process.StartTime -gt 0){
$ts = (New-TimeSpan -Start $process.StartTime -ea si).TotalSeconds
$cpuUsagePercentage = [math]::Round($process.CPU *100 / $ts / $cpu.numberoflogicalprocessors, 2)
}
else{
$cpuUsagePercent = 0
}
$_ | Add-Member -MemberType NoteProperty -Name "CpuUsage" -Value $cpuUsagePercentage
$_
} | Sort-Object -Property CpuUsage -Descending | Select-Object Name, ProcessId, CpuUsage -First 3
Script fails on this line with error from the title [System.Object[]] does not contain a method named 'op_Division'
$cpuUsagePercentage = [math]::Round($process.CPU *100 / $ts / $cpu.numberoflogicalprocessors, 2)
I debugged this and put breakpoint on above line and values are:
$process.CPU=699
$ts=737146,1126995
$cpu.numberoflogicalprocessors=1
No idea why it works on some machine while it fails on other
$cpu variable:
__GENUS : 2
__CLASS : Win32_Processor
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
NumberOfCores : 1
NumberOfLogicalProcessors : 1
PSComputerName :
__GENUS : 2
__CLASS : Win32_Processor
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
NumberOfCores : 1
NumberOfLogicalProcessors : 1
PSComputerName :
__GENUS : 2
__CLASS : Win32_Processor
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
NumberOfCores : 1
NumberOfLogicalProcessors : 1
PSComputerName :
__GENUS : 2
__CLASS : Win32_Processor
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
NumberOfCores : 1
NumberOfLogicalProcessors : 1
PSComputerName :
__GENUS : 2
__CLASS : Win32_Processor
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
NumberOfCores : 1
NumberOfLogicalProcessors : 1
PSComputerName :
__GENUS : 2
__CLASS : Win32_Processor
__SUPERCLASS :
__DYNASTY :
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
NumberOfCores : 1
NumberOfLogicalProcessors : 1
PSComputerName :