我是 PowerShell 的新手,提前道歉。我从这里找到的脚本开始:通过电子邮件获取事件日志内容(非常感谢和感谢)并将其调整为我需要它的工作方式。基本上,当这个错误代码发生时,它每 60 秒发布一次,所以我只想要每隔一段时间发送一封电子邮件,其中包含在基本表格中转换为 HTML 的 20 个最新事件。在 ISE 中执行脚本时一切正常,但是在常规 PowerShell 控制台中运行或作为计划任务时不会发送电子邮件。需要注意的一点是,我可以在 PowerShell 控制台中将所有内容运行到电子邮件部分,并将其写入 HTML 文件EventID-To-HTML | Out-File -FilePath $filePath -Append
。作为新手,我确信我处理事情的方式并不完全正确,因此我们始终感谢反馈。非常感谢
Clear-Host
# ========================
# Collection Data Section
# ========================
function EventID-To-HTML($ComputerName = $env:COMPUTERNAME) {
$FROMTIME = (Get-Date).AddMinutes(-60)
$Event = get-eventlog -log Application -newest 20 | where {$_.EventID -eq 7071 -AND $_.TimeGenerated -gt $FROMTIME}
$eventstring = @()
Foreach ($i in $Event) {
$eventstring += $i.Message + ", " +$i.TimeGenerated
}
if ($eventstring -eq $NULL){exit}
$GetEventDate = get-eventlog -log Application -newest 1 | where {$_.EventID -eq 7071 -AND $_.TimeGenerated -gt $FROMTIME}
$EventDate = $GetEventDate.TimeGenerated
$htmlStart = "<HTML>
<HEAD>
<style>
body {background-color:rgb(238, 238, 238);}
body, table, td, th {font-family:Calibri; color:Black; Font-Size:11pt}
th {font-weight:bold; background-color:rgb(78, 227, 48);}
td {background-color:rgb(255, 190, 0);}
</style>
</HEAD>
<BODY><div align=center>
<h2><b><br><br>Security Alert: <span Style='font-style:normal; color:Blue'>**Camera(s) Down**</span></b></h2>
<p><b><br>This event occurred at: <span Style='font-style:italic; color:Blue'>$EventDate on $ComputerName</span></b></p>"
$htmlEnd = ''
$htmlStart
$eventstring | ForEach-Object {Add-Member -InputObject $_ -Type NoteProperty -Name Camera -Value $_; $_} | ConvertTo-Html -Property Camera
#$eventstring | %{ New-Object PsObject -Prop @{Length = $_.Length; String = $_} } | ConvertTo-HTML
$htmlStart = ''
$htmlStart = $htmlStart + "<br><br><br><i><span Style='color:red'>This report has been generated by software</i> <br><i>Please DO NOT reply.</i></div>"
$htmlStart
$htmlEnd = ''
$htmlEnd
}
# ======================
# Email Section
# ======================
# Make sure $eventstring has something in it first as to not send an empty message
if ($eventstring.count -ge 1) {
$strFrom = "Sender@domain.com"
$strTo = "recipient@domain.com"
$strSubject = "Subject"
$strSMTPServer = "SMPT Server name"
$objEmailMessage = New-Object system.net.mail.mailmessage
$objEmailMessage.From = ($strFrom)
$objEmailMessage.To.Add($strTo)
$objEmailMessage.Subject = $strSubject
$objEmailMessage.IsBodyHTML = $true
$objEmailMessage.Body = EventID-To-HTML
$objSMTP = New-Object Net.Mail.SmtpClient($strSMTPServer)
$objSMTP.Send($objEmailMessage)
}