用于向我发送事件查看器错误/警告/失败的电子邮件警报的PowerShell脚本

bgtovc5b  于 2022-12-18  发布在  Shell
关注(0)|答案(2)|浏览(86)

我正在尝试编辑下面的脚本,以利用任务计划程序发送给我一封电子邮件通知每次错误/警告/失败记录在我们的服务器事件查看器。
重要信息:

  • 我是PowerShell的全新用户
  • 发件人电子邮件和收件人电子邮件都是我公司outlook exchange服务器的一部分
  • 我需要此脚本从事件查看器中的“Windows”日志文件夹提取事件
  • 我也相信这个脚本需要安装一个模块,我正在努力弄清楚如何安装
  • 我需要知道要编辑什么(我相信参数)以适合我的特定使用情形

提前感谢您的帮助。下面是https://github.com/blachniet/blachniet-psutils/blob/master/Send-EventEntryEmail.psm1的脚本:

Import-Module $PSScriptRoot\Send-EventEntryEmail.psm1

Function Send-EventEntryEmail {

[CmdletBinding()]
    param(
        [Parameter()]
        [string] $LogName = "System""Application""Security,
    
        [Parameter(Mandatory=$true)]
        [string] $Source,
    
        [Parameter()]
        [int] $Newest = 5,

        [Parameter()]
        [string[]] $EntryType = "Error""Warning""Failure",
    
        [Parameter(Mandatory=$true)]
        [string] $SmtpUser = "helpdesk@mydomain.com",
    
        [Parameter(Mandatory=$true)]
        [string] $SmtpPassword = "passwordexample",
    
        [Parameter()]
        [int] $SmtpPort = 587,
    
        [Parameter()]
        [string] $SmtpServer = "smtp.mail.outlook.com",
    
        [Parameter(Mandatory=$true)]
        [string] $MailFrom = "helpdesk@mydomain.com",
    
        [Parameter(Mandatory=$true)]
        [string] $MailTo = "myemail@mydomain.com,
    
        [Parameter()]
        [string] $Subject = "EventLogAlert",

    )

    # Get the event entries.
    $eventEntries = Get-EventLog -LogName $LogName -Source $Source -Newest $Newest -EntryType $EntryType

    # Create a table row for each entry.
    $rows = ""
    foreach ($eventEntry in $eventEntries){
        $rows += @"
        <tr>
            <td style="text-align: center; padding: 5px;">$($eventEntry.TimeGenerated)</td>
            <td style="text-align: center; padding: 5px;">$($eventEntry.EntryType)</td>
            <td style="padding: 5px;">$($eventEntry.Message)</td>
        </tr>
"@
    }

    # Create the email.
    $email = New-Object System.Net.Mail.MailMessage( $MailFrom , $MailTo )
    $email.Subject = $Subject
    $email.IsBodyHtml = $true
    $email.Body = @"
    <table style="width:100%;border">
        <tr>
            <th style="text-align: center; padding: 5px;">Time</th>
            <th style="text-align: center; padding: 5px;">Type</th>
            <th style="text-align: center; padding: 5px;">Message</th>
        </tr>
    
    $rows
    </table>
"@

    # Send the email.
    $SMTPClient=New-Object System.Net.Mail.SmtpClient( $SmtpServer , $SmtpPort )
    $SMTPClient.EnableSsl=$true
    $SMTPClient.Credentials=New-Object System.Net.NetworkCredential( $SmtpUser , $SmtpPassword );
    $SMTPClient.Send( $email )
}

Export-ModuleMember Send-EventEntryEmail

以下是我运行当前脚本时在伊势中遇到的错误:

At line:17 char:34
+         [string[]] $EntryType = "Error""Warning""Failure",
+                                  ~
Missing ')' in function parameter list.
At line:35 char:49
+         [string] $MailTo = "myemail@mydomain.com,
+                                                 ~
Missing argument in parameter list.
At line:37 char:20
+         [Parameter()]
+                    ~
An expression was expected after '('.
At line:38 char:45
+         [string] $Subject = "EventLogAlert",
+                                             ~
Missing expression after ','.
At line:3 char:31
+ Function Send-EventEntryEmail {
+                               ~
Missing closing '}' in statement block or type definition.
At line:40 char:5
+     )
+     ~
Unexpected token ')' in expression or statement.
At line:78 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInFunctionParameterList
5sxhfpxr

5sxhfpxr1#

您可以通过电子邮件订阅事件日志,方法是设置一个计划任务,该任务将接收新事件的通知并通过电子邮件发送。
在任务计划程序中,首先添加由“发生事件时”触发的任务。要订阅特定的日志/源/事件ID组合,请使用“基本”。要订阅许多事件,请使用“自定义”,并使用符合您需要的事件筛选器。

无论哪种方式,第二步都是一个powershell脚本,它可以检查事件并通过电子邮件转发它。这可以通过在任务计划程序中添加一个操作来完成,该操作调用powershell.exe并传递参数.\MyDelightfulScriptName.ps1 -eventRecordID $(eventRecordID) -eventChannel $(eventChannel)

然后按照bergerb的说明将事件记录ID和通道传递给powershell。
要访问记录的事件,powershell脚本使用Get-WinEventEventRecordID筛选器:

# Collects all named paramters (all others end up in $Args)
param($eventRecordID,$eventChannel)

$event = Get-WinEvent -LogName $eventChannel -FilterXPath "<QueryList><Query Id='0' Path='$eventChannel'><Select Path='$eventChannel'>*[System[(EventRecordID=$eventRecordID)]]</Select></Query></QueryList>";

Send-MailMessage `
    -From 'evetlog@server.domain.local' `
    -To 'admin@domain.local' `
    -Subject ($event.Message.Split([Environment]::NewLine)[0]) `
    -SmtpServer 'smtp.domain.local' `
    -Body ($event.Message);
bwleehnv

bwleehnv2#

非常重要的信息缺失:创建Trigger之后,需要调整任务的XML(添加ValueQueries)!
(导出、调整、导入)

<EventTrigger>
  <Enabled>true</Enabled>
  <Subscription> ... </Subscription>
  <ValueQueries>
    <Value name="eventRecordID">Event/System/EventRecordID</Value>
    <Value name="eventChannel">Event/System/Channel</Value>
  </ValueQueries>
</EventTrigger>

值得阅读:
https://learn.microsoft.com/de-de/archive/blogs/wincat/trigger-a-powershell-script-from-a-windows-event
我还调整了脚本以允许身份验证,将其调整为UTF-8以便äöü可以工作,并在主题中添加了一些信息:

# Collects all named paramters (all others end up in $Args)
param($eventRecordID,$eventChannel)

$event = Get-WinEvent -LogName $eventChannel -FilterXPath "<QueryList><Query Id='0' Path='$eventChannel'><Select Path='$eventChannel'>*[System[(EventRecordID=$eventRecordID)]]</Select></Query></QueryList>";

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

Send-MailMessage `
    -From '<sender>' `
    -To '<receiver>' `
    -Subject "$env:COMPUTERNAME EVENTLOG $($event.Message.Split([Environment]::NewLine)[0][0..30] -join '')" `
    -SmtpServer '<server>' `
    -Credential $cred `
    -Body ($event.Message) `
    -Port 587 `
    -UseSsl `
    -Encoding UTF8;

相关问题