Powershell查看日志并发送电子邮件通知

时间:2019-05-29 02:44:13

标签: powershell

脚本新手。我需要创建Powershell脚本的帮助,该脚本将查看日志文件并搜索关键字,例如失败/失败,并且关键字存在,请发送一封电子邮件,最后50行。

我有部分脚本可以使用,但是我很难将其放在一起。

查看日志并打印行

$PATH="C:\tmp\test.log"
Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }

发送到SMTP服务器的电子邮件已排序并正常工作

$From = "test@foobar.com"
$To = "test2@foobar.com"

$Subject = "Failed notification"
$Body = "This is what I want to say"
$SMTPServer = "smtp.foobar.com"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort

我知道我需要一个IF语句来比较内容并设置为true,然后发送电子邮件。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

在学习的同时,如果需要提醒自己会返回什么,可能更容易明确。

[string] $PATH="C:\tmp\test.log"
[string[]] $failedRows = Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
# Email to SMTP server sorted and working

[string] $From = "test@foobar.com"
[string] $To = "test2@foobar.com"
[string] $Subject = "Failed notification"
[string] $Body = "This is what I want to say"
[string] $SMTPServer = "smtp.foobar.com"
[string] $SMTPPort = "25"
if( $failedRows -and $failedRows.Length -gt 0) {
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}

记住powershell是weakly typed。像vscode这样带有powershell extension的编辑器会有所帮助,并且您会看到有关如何改进代码的建议。

$PATH="C:\tmp\test.log"
$failedRows = Get-Content $PATH -Tail 50 | Where-Object { $_.Contains("fail") }
# Email to SMTP server sorted and working

$From = "test@foobar.com"
$To = "test2@foobar.com"
$Subject = "Failed notification"
$Body = "This is what I want to say"
$SMTPServer = "smtp.foobar.com"
$SMTPPort = "25"
if( $failedRows -and $failedRows.Length -gt 0) {
    Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}