所以我发布了这个脚本并获得了一些帮助:
#Command to get list of folders with logfiles where the logfile is at least 30 minutes old send results to variable.
$varlogfile = Get-ChildItem -Path "drive:\folder" -Recurse -Include "logfile" | Where-Object {$_.LastWriteTime -le ((Get-Date).AddMinutes(-30))}
#Add a carriage return to results contained in the variable so email is easier to read
$varlogfile = $varlogfile -join "`r`n"
#Email setup from this line down to next comment
$SMTPServer = "email.server"
$From = "Administrator <administrator@place.com>"
$To = "email","email2"
$Subject = "A Logfile older than 30 minutes has been detected"
$Body = "Logfile(s) older than 30 minutes have been detected in the following folder(s):
$varlogfile
Please login and attempt to process the files manually, if the manual process fails, open a ticket with someone.
From the Admin
"
#Email setup above this line
#If statement that looks for the text blah in the variable, if found email is sent.
if($varlogfile -match "blah")
{
#Command to send email
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer
}
exit 0;
所有这一切都很完美。
但事情就是这样。在周末有时我们可能会得到一个卡住的日志文件,直到星期一早上才能解决,如果发生这种情况,能够关闭警报会很好。
现在我对powershell很新,这个脚本一直是我的学习经历。我看到它的方式是我有3个选择:
如果get-childitem看到logfile和logfile.stop,则不会返回结果。
get-childitem生成了$ varlogfile后,搜索$ varlogfile for logfile.stop并从中删除logfile和logfile.stop行。
从头开始重写整个事情并以更好的方式生成$ varlogfile,以便更容易处理结果。
想法和意见?我倾向于方法2,因为我认为我可以解决这个问题,但我很好奇这是否是一种痛苦的方式。我真的很喜欢你的意见。
谢谢大家!
答案 0 :(得分:1)
我认为您的当前计划正在走上正确的道路,所以我会在方法#2的帮助下,在发送电子邮件时创建.sent文件,以防止电子邮件多次发送。
我们的第一步:当发送电子邮件时,我们创建一个新的文件标题$ logfile.MessageSent或类似的东西。这样做可以发送电子邮件,并且我们也可以创建一个标志,我们可以稍后在文件系统中搜索,以确定我们是否发送了另一封电子邮件。
#If statement that looks for the text blah in the variable, if found email is sent.
if($varlogfile -match "blah")
{
#Command to send email
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer
New-Item -path $varLogfile.Sent -itemType File
}
我们的第二步:修改我们的Get-ChildItem查询以搜索标志:
$varlogfile = Get-ChildItem -Path "drive:\folder" -Recurse -Include "logfile" |
Where-Object {$_.LastWriteTime -le ((Get-Date).AddMinutes(-30))} |
? "($_.BaseName).sent" -notin (Get-ChildItem -Recurse -Include "*.sent" -Path "drive:\folder" | Where-Object {$_.LastWriteTime -le ((Get-Date).AddMinutes(-30))})
无可否认,对$ varlogfile步骤的第二次修改很难理解。以下是我改变它的方式:
你唯一需要做的就是添加一个清理任务来定期删除.sent文件,你就可以了。
如果您对此方法有任何疑问,请与我们联系,因为我想确保您理解并帮助您学习。