抱歉,我刚刚开始编写PowerShell脚本。我试图使用脚本在事件查看器中发生事件(错误)时发送电子邮件。我不想使用事件查看器中包含的功能,因为它不适用于所有操作系统。这是我现在在脚本中的内容,但是我无法从剪切的错误中导入消息或数据。
$event = Get-EventLog -LogName Application -Source "My Script-1" | where {$_.eventID -eq 1}
if ($event.EntryType -eq "Error")
{
[string]$EmailBody = Event.Data
$EmailFrom = "Test@google.com"
$EmailTo = "lmill130@kent.edu"
$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."
我创建了一个任务,当该事件被切断时,它会运行第一个脚本。
我在互联网上搜索过,但我没有运气。请帮助。
答案 0 :(得分: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 = "Test@google.com"
$EmailTo = "lmill130@kent.edu"
$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
}
答案 1 :(得分:0)
替换[string]$EmailBody = Event.Data
[string]$EmailBody = $Event.Data
使用Message而不是数据总是更好,因为你对错误信息更加困扰,而不是将被捕获的数据。
希望它有所帮助。