Powershell Get-EventLog(简介)

问题描述 投票:0回答:2

对不起,我刚刚开始编写PowerShell脚本。我试图使用脚本在事件查看器中发生事件(错误)时发送电子邮件。我不想使用事件查看器中包含的功能,因为它不适用于所有操作系统。这是我现在在脚本中的内容,但是我无法从剪切的错误中导入消息或数据。

$event = Get-EventLog -LogName Application -Source "My Script-1" | where {$_.eventID -eq 1}

if ($event.EntryType -eq "Error")
{
    [string]$EmailBody = Event.Data
    $EmailFrom = "[email protected]"
    $EmailTo = "[email protected]"
    $EmailSubject = "This was sent from a PowerShell Script"
    $SMTPServer = "Example Server SMTP"
    Write-host "Sending Email Test"
    Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $EmailBody -SmtpServer $SMTPServer
}
else 
{
    write-host "No error found"
    write-host "Here is the log entry that was inspected:"
    $event
}

如果我将自己的字符串放在$ EmailBody中,那么它没有问题但是当我尝试从事件中获取数据时我没有运气。

这是我用来创建测试事件的脚本。

#New-EventLog -LogName Application -Source "My Script-1" 
Write-EventLog -LogName Application -Source "My Script-1" -EntryType Error -
EventId 1 -Message "This is a test Entry." 

我创建了一个任务,当该事件切断时,它会运行第一个脚本。

我在互联网上搜索过,但我没有运气。请帮忙。

powershell cmdlets
2个回答
0
投票

这可能是因为Event.Data没有返回任何东西。

它必须是$event.Data,但我认为你应该使用$event.Message来获取错误的信息消息。

所以一起看起来像这样:

$event = Get-EventLog -LogName Application -Source "My Script-1" | where {$_.eventID -eq 1}

if ($event.EntryType -eq "Error")
{
    [string]$EmailBody = $event.Data
    #or [string]$EmailBody = $event.Message

    $EmailFrom = "[email protected]"
    $EmailTo = "[email protected]"
    $EmailSubject = "This was sent from a PowerShell Script"
    $SMTPServer = "Example Server SMTP"
    Write-host "Sending Email Test"
    Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -Body $EmailBody -SmtpServer $SMTPServer
}
else 
{
    write-host "No error found"
    write-host "Here is the log entry that was inspected:"
    $event
}

0
投票

替换[string]$EmailBody = Event.Data

[string]$EmailBody = $Event.Data

并且它总是更好地使用Message而不是数据导致您更加困扰错误消息而不是将被捕获的数据。

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.