我是PowerShell的全新用戶,請事先道歉。我從這裏找到的腳本開始:Getting Event Log contents by email(巨大的功勞和感謝),並調整它到我需要它的工作。基本上,當這個錯誤代碼發生時,它每60秒發佈一次,所以我只需要每隔一段時間就會收到一封電子郵件,其中20個最近的事件在基本表格中轉換爲HTML。在ISE中執行腳本時一切正常,但是在常規PowerShell控制檯中運行時不會發送電子郵件,或者作爲計劃任務發送。有一點需要注意,我可以在PowerShell控制檯中將所有內容運行到電子郵件部分,並將其寫入HTML文件EventID-To-HTML | Out-File -FilePath $filePath -Append
。作爲新人,我確信我沒有正確處理事情,所以反饋總是值得讚賞的。非常感謝PowerShell腳本不會運行在ISE之外
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 = "[email protected]"
$strTo = "[email protected]"
$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)
}
謝謝,我想我需要更多的澄清。如果我在全球範圍內創建$ eventstring,在我看來,它似乎可以解決它,對嗎? – user2921987
你可以,但使用全局變量通常被認爲是不好的做法。還有其他方法可以避免範圍界定問題。一個是使用arralist而不是數組。我用一個例子更新了答案。 – mjolinor
+1倡導反對全球變量。 – Neolisk