PowerShell script to find the process CPU usage & send alert.

<form class=“ipsForm ipsForm_vertical” accept-charset=“utf-8” action=“https://discussions.citrix.com/topic/create/1316/” enctype=“multipart/form-data” method=“post” data-action=“add” data-controller=“citrix.front.topic.createtopicform” data-swapid=“ctx-forums-topic-form” data-ipsform="">

Hi there…I am trying to monitor few process . I have a PowerShell script mentioned below, but trying to update the output to get high CPU usage (over 25% threshold) for processes for certain time period (over 15 minutes). Is there a way to monitor processes for certain that time period and send email alert if it stays for long period of time ? Pls advice me ?

[pre]

$Output = ‘C:\temp\Result.txt’
$ServerList = Get-Content ‘C:\temp\Servername.txt’

$ScriptBLock = {

$CPUPercent = @{
Label = ‘CPUUsed’
Expression = {
$SecsUsed = (New-Timespan -Start $.StartTime).TotalSeconds
[Math]::Round($
.CPU * 10 / $SecsUsed)
}
}

$MemUsage = @{
Label =‘RAM(MB)’
Expression = {
[Math]::Round(($_.WS / 1MB),2)
}
}
Get-Process | Select-Object -Property Name, CPU, $CPUPercent, $MemUsage,
Description |
Sort-Object -Property CPUUsed -Descending |
Select-Object -First 15 | Format-Table -AutoSize
}

foreach ($ServerNames in $ServerList) {

“CPU & Memory Usage in $serverNames” | Out-File $Output -Append

Invoke-Command -ScriptBlock $ScriptBLock -ComputerName $ServerNames |
Out-File $Output -Append
}

[/pre]

 

</form>

Unless you keep track of the historical data for monitoring, operating systems by default do not record the metrics of the resources.

So, please enable monitoring on your servers and run your PowerShell scripts against the metrics data.

[quote quote=136028]Unless you keep track of the historical data for monitoring, operating systems by default do not record the metrics of the resources.

So, please enable monitoring on your servers and run your PowerShell scripts against the metrics data.

[/quote]

Thanks for your reply. Do you mean like performance monitor ? Do you have any resources that you can share pls ?

It’s basic and it doesn’t take into account the time used by the Get-Counter cmdlet itself, but it should do the job.

$CPUThreshold = 25
$SamplesIntervalInSeconds = 10
$MaximumSamples = 900
$SuccessiveMatchingSamples = 0

$MailParams = @{
    'SmtpServer'  = 'smtp.mycompany.com'
    'Port'        =  25
    'Priority'    = 'Normal'
    'From'        = 'sender@mycompany.com'
    'To'          = 'mainrecipient@mycompany.com'
    'Cc'          = 'copyrecipient@mycompany.com'
    'Bcc'         = 'hiddenrecipient@mycompany.com'
    'Subject'     = 'Mail title'
    'Body'        = 'This is the content of my mail'
    'BodyAsHtml'  =  $false
    'Attachments' = 'c:\\MyFile.txt'
} 

While($true){
        
    If(((Get-Counter -Counter '\processor(_total)\% processor time').CounterSamples.CookedValue) -gt $CPUThreshold){
        
        $SuccessiveMatchingSamples++
        
        If($SuccessiveMatchingSamples -gt $MaximumSamples){
            
            Send-MailMessage @MailParams

            $SuccessiveMatchingSamples = 0
        }
    }
    else{
        $SuccessiveMatchingSamples = 0
    }
    
    Start-Sleep -Seconds $SamplesIntervalInSeconds
}

We all love ourselves some PowerShell, but PowerShell is not the appropriate answer for everything.
Even trying to do this, can cause additional CPU spikes, so that must be considered.

Approaches (potentially multi-step):

First -

How To Use Server Manager To Configure Performance Alerts https://redmondmag.com/articles/2016/07/05/server-manager-to-configure-performance-alert.aspx

Second -
Use WMI Event Monitors, to watch for specific and take action(s).

There are purpose built solutions for such things, example:

The WMI CPU monitor can provide you with several CPU metrics, namely:
<li>&#x25fe; total active time</li>

<li>&#x25fe; user time</li>

<li>&#x25fe; system time</li>

<li>&#x25fe; interrupts per second</li>

<li>&#x25fe; context switches per second</li>

https://iphostmonitor.com/monitor-cpu-usage-over-wmi.html

Enable monitoring of CPU utilization on Windows systems https://wiki.opennms.org/wiki/Enable_monitoring_of_CPU_utilization_on_Windows_systems

So, monitor for high CPU, regardless of process, the get all running processes sorted by CPU, start a timer, take action based on exceeding that specific time range.