Script – Windows – Para verificar uso do CPU derrubar um processo e enviar um e-mail

Script desenvolvido em powershell

Function fmail {
$username = ‘ti.seguranca@pinhais.pr.gov.br’
$password = ‘Senha’

$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($username, $secpasswd)

$properties=@(
@{Name=”Process Name”; Expression = {$_.name}},
@{Name=”CPU (%)”; Expression = {$_.PercentProcessorTime}},
@{Name=”Memory (MB)”; Expression = {[Math]::Round(($_.workingSetPrivate / 1mb),2)}}
)

$__MSG=(Get-WmiObject -class Win32_PerfFormattedData_PerfProc_Process |
Sort-Object -Property PercentProcessorTime -Descending |
Select-Object $properties )

$MSG = “O processador do servidor esta com a utilizacao acima dos 98% o processo DsPcSrv foi interompido “+”`r`n”+”`r`n”
Foreach ($_MSG in $__MSG){
$MSG=[String]($MSG+$_MSG+”`r`n”)
}

Send-MailMessage -Credential $mycreds -From ‘ti.seguranca ‘ -To ‘ti.seguranca ‘ -Subject “WARNING CPU LOAD SRVIMPRESSAO” -Body $MSG -UseSsl -SmtpServer ‘webmail.pinhais.pr.gov.br’ -Port 587
}

Try {
$Threshold = 98
$CpuLoad2 = (Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average )
$CpuLoad = ([String]$CpuLoad2).split(“=”)
$CpuLoad = $CpuLoad[1].split(“}”)

Write-Host “CPU load is” $CpuLoad[0] “%”

IF([int]$CpuLoad[0] -gt $Threshold) {
Write-Host “CPU load greater than !” $Threshold “%”
Write-Host “Script Check Failed.”
taskkill /IM “DsPcSrv.exe” /F
fmail
} Else {
Write-Host “Script Check Passed.”
}

}Catch {
Write-Host “Script Check Failed..”$_.Exception.Message
}