# Jonathan Medd, Alan Renouf # http://jonathanmedd.blogspot.com/2009/01/using-powershell-to-monitor-vmware.html # check the cpu.usage.average statistic of a period of the last few minutes (watch out for the -IntervalMins parameter it can produce a period slightly different to what you would expect) and if its over 99% run the CheckHighCPU function and send the results by email. # Requires: VI Toolkit Function EmailWarning () { param ($ServerName,$Attachment) #Email warning Write-Output "Creating E-Mail Structure" $smtpServer = "servername" $msg = new-object Net.Mail.MailMessage $att = new-object Net.Mail.Attachment($attachment) $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "sender" $msg.To.Add("recipient") $msg.Subject = "Server Warning - High CPU on $Servername" $msg.Body = "$Servername has a CPU value of $HighCPU %" $msg.Attachments.Add($att) Write-Output "Send E-Mail" $smtp.Send($msg) $att.Dispose(); } Function CheckHighCPU () { param ($Target) $procs_total = Get-WmiObject -Class Win32_PerfRawData_PerfProc_Process -Filter 'name="_total"' -ComputerName $Target $procs = Get-WmiObject -Class Win32_PerfRawData_PerfProc_Process -Filter 'name<>"_total"' -ComputerName $Target [int64]$totalpercentuser = 0 foreach ($proc in $procs_total) { $totalpercentuser = $totalpercentuser + $proc.PercentUserTime} [decimal] $perc = [System.Convert]::ToDecimal($totalpercentuser) $myCol = @() foreach ($proc in $procs) { $proc_perct = (($proc.PercentUserTime / $perc) * 100) if ($proc_perct -gt 1){ $Process = Get-WmiObject win32_process -ComputerName $target | where {$_.ProcessID -eq $proc.IDProcess} $MYInfo = "" | select-Object Name, CPUUsage,Owner, ProcessID $MYInfo.Name = $proc.name $MYInfo.ProcessID = $proc.IdProcess $MYInfo.CPUUsage = [Math]::Round($proc_perct, 0) $MYInfo.Owner = $process.GetOwner().user $myCol += $MYInfo } } $myCol | Sort-Object CPUUsage -Descending | Out-File $file EmailWarning $VMname $file } Connect-VIServer servername $vms = Get-Cluster | where {$_.name -eq "ClusterName"} | get-vm $time = Get-Date do { foreach ($vm in $vms) { $VMname = $vm.name $filename = $VMname + '.txt' $file = "C:\Scripts\$filename" $stats = Get-Stat -entity $vm -IntervalMins 2 -stat cpu.usage.average -MaxSamples 1 write-host $VMname $stats if ($stats.value -ge 99) { $HighCPU = $stats.value Write-Host "Warning!" -ForegroundColor red CheckHighCPU $VMname } else { } } Start-Sleep -Seconds 30 } until ($time.hour -ge 17)