2015-04-06 18 views
1

所以我張貼,並得到一些幫助,這個腳本進行:尋找諮詢如何與工作PowerShell腳本

#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 <[email protected]>" 
$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種選擇:

  1. 保持了get-childitem從返回的結果,如果它看到日誌文件和logfile.stop。

  2. get-childitem產生$ varlogfile後,在$ loglog.stop中搜索$ varlogfile並從中刪除行logfile和logfile.stop。

  3. 從頭開始重寫整個事情,並以更好的方式生成$ varlogfile,以便更輕鬆地處理結果。

想法和觀點?我傾向於方法2,因爲我想我可以弄清楚,但我很好奇,如果這是一種痛苦的方式。我真的很喜歡你的意見。

謝謝大家!

+0

以下是我對您的問題的瞭解: - 您需要一個logFile Watcher。 - 觀察者應在生成新日誌文件時通過電子郵件向您發送電子郵件。 - 觀察者應處理大於30分鐘的長時間運行的寫入操作。 請澄清。 上述腳本中沒有事件代碼。 如何跟蹤新的日誌文件生成? 你是怎麼稱呼上面的腳本的? –

+0

腳本由任務管理器運行,每15分鐘運行一次。日誌文件的年齡很重要,因爲如果它存在30分鐘就意味着出現了問題,並且服務器不會完成該任務。因此,如果沒有找到日誌文件,或者發現日誌文件的年齡少於30分鐘,則不會生成電子郵件。 – Sean

+0

腳本如何由任務管理器執行? –

回答

1

我認爲你現在的計劃是正確的,所以我會在第二種方法的幫助下,在發送電子郵件時創建一個.sent文件,以防止電子郵件多次發送。

我們的第一步:發送電子郵件時,我們創建一個新文件title $ 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步驟是很難理解,無可否認。這裏是如何我已經改變了它:

  • 得到一個點燃的文件的驅動器\文件夾路徑,遞歸和日誌文件包括:
  • 凡LastWriteTime是超過30分鐘
  • 當filename.sent在同一目錄

你需要做的唯一的其他東西沒有找到的就是添加一個清除任務,定期刪除.sent文件,你是好去。

如果您對此方法有任何疑問,請讓我知道,因爲我想確保您瞭解並幫助您學習。

+0

我目前無法測試,但我想我明白了。儘快我可以測試我會盡快回復你,但也許一週左右。謝謝! – Sean