Send email alert from Performance Monitor using PowerShell script (检测windows服务器的cpu 硬盘 服务等性能,发email的...

本文介绍如何解决Windows Server 2008 R2中性能监视器警报无法通过邮件发送的问题。主要步骤包括:正确传递警报参数到PowerShell脚本,并确保调用已定义的邮件发送函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have created an alert in Performance Monitor (Windows Server 2008 R2) that should be triggered whenever \Processor(_Total)\% Processor Time is Above 10 (a small value just to guarantee that the condition for sending the alert is always met). You can see the Alert Task properties in the image.

enter image description here

In addition, I have also created a new task in the Task Scheduler that will run whether the user is logged on or not, and it will run with highest privileges. The trigger for this task has the following properties:

  • Begin the task: On an event
  • Settings: Basic
  • Log: System
  • Source: Processor

The Actions (and this is the part I don't know if it's correct) has the following settings:

  • Action: Start a program
  • Program/script: the path to a PowerShell script to send an email.

The PowerShell code is the following ($name, $date, $counter, $threshold, $value are supposed to come from the Performance Monitor data collector set alert task properties, as in the image above):

function SendMail ($name, $date, $counter, $threshold, $value) {
  $MailMessage = New-Object Net.Mail.MailMessage
  $MailMessage.To.Add("myemail@blah.bleh")
  $MailMessage.From = "do-not-reply@blah.bleh"
  $MailMessage.Subject = "ALERT - Performance Monitor"
  $MailMessage.IsBodyHtml = $True

  $MailMessage.Body = @"
    <html><head></head><body>
    The following counter needs attention:<BR><BR>
    Name: $($name)<BR>
    Date: $($date)<BR>
    Counter: $($counter)<BR>
    Threshold: $($threshold)<BR>
    Actual Value: $($value)<BR>
    <FONT face=Courier>$($html)</FONT>
    <BR>
    --- Automatically generated with SENDMAIL function ---
    </body>
    </html>
"@

  $SmtpClient = New-Object Net.Mail.SmtpClient("blah.bleh")
  $SmtpClient.Send($MailMessage)
}

Once the task is started, I have the following in the History: Task Started, Action Started, and Created ask Process. The email is never sent though.

I tried sending an email using the Action: Send an email, and it worked fine. Does anyone know what could be wrong?

share |improve this question
 
 
                                                                                        
                                                                                                                   
                                                                                                 
 
                                                                     
  
                                                                                                                   
                                                                        

1 Answer                                 1

     up vote 4down voteaccepted

There are basically two things to address that should make this work for you. 

  1. Get the alert parameters correctly passed to your script.
  2. Actually call the function defined in your script.

We'll start with the parameters.  On the Alert Task tab of your alert (pictured above), edit the Task Arguments field and replace:

{name}{date}{counter}{threshold}{value}

with:

"{name}" "{date}" "{counter}" "{threshold}" "{value}"

Your parameters are basically being parsed as a space-separated string value, so we add double-quotes around each individual parameter token to handle values that include spaces, and we add a space between each individual parameter token so that we'll be able to tell one parameter from the next.

Then, for the action of your scheduled task (named "Processor Monitoring") you have to tell it to expect parameters from the alert and to pass those parameters to the PowerShell script.

enter image description here

Your Action is correct, i.e. "Start a program". 

For the Program/script field, enter "powershell.exe" (or browse for the full path). 

And for the Add Arguments field, enter this:

-File C:\path\to\your\PowerShell\scripts\perfmon_send_email.ps1 $(Arg0)

Where perfmon_send_email.ps1 is the script file containing your SendMail() function as described above. 

This bit was kind of finicky, so there may be other ways to set this up, but explicitly using the -File parameter made a difference for my tests.  The $(Arg0) part is what gets replaced with the parameter string from the Alert when the scheduled task executes PowerShell to run your script.

So that should make the Alert parameters available to your PowerShell script.  Now all you have to do is actually call the function you've already defined.  Add the following to the end of your script (after the function definition):

# Get parameter values by position and pass them to the SendMail() function.
SendMail $args[0] $args[1] $args[2] $args[3] $args[4]

$args is an array containing the parameter values passed to a script file called from the command line, which is exactly what we configured the scheduled task to do. 

Since we know the alert will always send the same values in the same order, i.e. name, date, counter, threshold, and value, we can just pull them from the command line arguments based on position and pass them to the SendMail() function. 

Note that there are more robust ways to process command line arguments, but this should be sufficient for your purposes.

<think>我们已经在之前的回答中涉及了部分PowerShell监控Oracle的内容,现在需要更详细地展开实时性能监控与警报生成的具体方案。 核心思路:通过PowerShell调用Oracle.ManagedDataAccess.Client连接数据库,执行性能查询,根据阈值触警报(邮件或日志)。 步骤: 1. 安装必要的模块(如Oracle客户端库) 2. 编写SQL查询获取性能数据(如等待事件、会话数、表空间使用率等) 3. 设置阈值并比较 4.警报(邮件、事件日志等) 5. 设置定时任务循环执行 注意:由于是实时监控,可能需要循环执行或作为后台服务运行。</think>### 利用PowerShell监控Windows服务器Oracle性能并生成警报 以下是完整的实现方案,涵盖实时监控、阈值警报和多种通知方式: #### 1. **核心监控脚本** (`OracleMonitor.ps1`) ```powershell # 加载Oracle客户端库 Add-Type -Path "C:\app\oracle\product\19c\dbhome_1\ODP.NET\bin\4\Oracle.DataAccess.dll" # 监控参数配置 $thresholds = @{ SessionLimit = 100 # 活动会话阈值 CPUPercent = 90 # CPU使用率阈值 Tablespace = 85 # 表空间使用率阈值 WaitEvent = 30 # 关键等待事件阈值(秒) } # 数据库连接配置 $connStr = "User Id=monitor_user;Password=P@ssw0rd;Data Source=ORCL" # 性能监控函数 function Get-OracleMetrics { $conn = New-Object Oracle.ManagedDataAccess.Client.OracleConnection($connStr) $conn.Open() $metrics = @{} # 活动会话数 $cmd = $conn.CreateCommand() $cmd.CommandText = "SELECT COUNT(*) FROM v`$session WHERE status='ACTIVE'" $metrics.Sessions = $cmd.ExecuteScalar() # CPU使用率 $cmd.CommandText = @" SELECT ROUND((SUM(VALUE)/1000000)/60,2) FROM v`$sysmetric WHERE metric_name='CPU Usage Per Sec' AND group_id=2 AND end_time > SYSDATE-1/24/60 "@ $metrics.CPU = $cmd.ExecuteScalar() # 表空间使用率 $cmd.CommandText = "SELECT MAX(used_percent) FROM dba_tablespace_usage_metrics" $metrics.Tablespace = $cmd.ExecuteScalar() # 关键等待事件 $cmd.CommandText = "SELECT event, time_waited FROM v`$system_event WHERE wait_class='System I/O'" $reader = $cmd.ExecuteReader() while ($reader.Read()) { $metrics[$reader.GetString(0)] = $reader.GetDecimal(1) } $conn.Close() return $metrics } # 警报生成函数 function Send-Alert { param($metric, $value, $threshold) $subject = "[ORACLE ALERT] $metric 超出阈值" $body = @" 服务器: $env:COMPUTERNAME 监控项: $metric 当前值: $value 阈值: $threshold 时间: $(Get-Date) "@ # 送邮件 Send-MailMessage -From "oracle_monitor@company.com" -To "dba@company.com" -Subject $subject -Body $body -SmtpServer "smtp.company.com" # 写入Windows事件日志 Write-EventLog -LogName "Application" -Source "OracleMonitor" -EntryType Warning -EventId 1001 -Message $body } ``` #### 2. **实时监控循环** (`Start-Monitor.ps1`) ```powershell # 导入监控模块 . .\OracleMonitor.ps1 # 实时监控循环(每60秒检查一次) while ($true) { $metrics = Get-OracleMetrics # 检查活动会话 if ($metrics.Sessions -gt $thresholds.SessionLimit) { Send-Alert -metric "活动会话数" -value $metrics.Sessions -threshold $thresholds.SessionLimit } # 检查CPU使用率 if ($metrics.CPU -gt $thresholds.CPUPercent) { Send-Alert -metric "CPU使用率" -value $metrics.CPU -threshold $thresholds.CPUPercent } # 检查表空间 if ($metrics.Tablespace -gt $thresholds.Tablespace) { Send-Alert -metric "表空间使用率" -value $metrics.Tablespace -threshold $thresholds.Tablespace } # 检查关键等待事件 $metrics.Keys | Where-Object { $_ -like "*db file*" } | ForEach-Object { if ($metrics[$_] -gt $thresholds.WaitEvent) { Send-Alert -metric "等待事件: $_" -value $metrics[$_] -threshold $thresholds.WaitEvent } } Start-Sleep -Seconds 60 } ``` #### 3. **Windows服务集成** ```powershell # 注册为Windows服务(需管理员权限) $serviceParams = @{ Name = "OracleMonitor" BinaryPathName = "powershell.exe -File C:\Scripts\Start-Monitor.ps1" DisplayName = "Oracle实时性能监控" StartupType = "Automatic" Description = "监控Oracle数据库性能送警报" } New-Service @serviceParams # 启动服务 Start-Service -Name OracleMonitor ``` #### 4. **高级警报选项** ```powershell # 短信警报(通过Twilio API) function Send-SMSAlert { param($message) $accountSid = "ACXXXXXXXXXXXXXXXX" $authToken = "YYYYYYYYYYYYYYYY" $url = "https://api.twilio.com/2010-04-01/Accounts/$accountSid/Messages.json" $body = @{ From = "+1234567890" To = "+0987654321" Body = $message } Invoke-RestMethod -Uri $url -Method Post -Body $body -Credential (New-Object System.Management.Automation.PSCredential($accountSid, (ConvertTo-SecureString $authToken -AsPlainText -Force))) } # 在Send-Alert函数中添加: Send-SMSAlert -message $body ``` #### 5. **最佳实践** 1. **安全增强**: - 使用加密的配置文件存储凭据 - 限制监控账户权限(仅授予SELECT_CATALOG_ROLE) 2. **性能优化**: ```powershell # 轻量级监控模式 $cmd.CommandText = "SELECT /*+ MONITOR */ ..." ``` 3. **日志管理**: ```powershell Start-Transcript -Path "C:\logs\oracle_monitor_$(Get-Date -Format yyyyMMdd).log" -Append ``` 通过此方案,可实现分钟级的Oracle性能监控,自动触邮件/短信/事件日志警报,并作为Windows服务持续运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值