Script to report 6009 "Unexpected Shutdown" once when schedule to run from task scheduler.


experts

i need schedule powershell script report 6008 event id "unexpected shutdown" once , send mail. have small code mentioned below but, script sends email repeatedly once found 6008 in system log. want send once , running in task scheduler report next 6008.

function service-state{

process {

 

get-eventlog -logname system -computername $_ | ? {if ($_.eventid -eq "6008") {


$x = $_.timegenerated

$y = $_.machinename


send-mailmessage -to "abc@abc.com" -from "abc@abc.com" -subject "the system $y shutdown unexpectedly @ $x" -body "the system $y shutdown unexpectedly @ $x" -smtpserver "gateway_server"

 

break

}

}

}
}

gc c:\serverlist.txt | service-state

ok, in order new 6008-events, need log time of last valid event has been found. , every time check again new events, need filter out newer last 1 found.

this script creates logfile each server , write time of last found event in it. when runs again, reads time file , checks if there newer events found. every server in list , after 1 mail, containing new events.
try , let me know if there problems. :)  

$logpath = "d:"   ### path logfiles  function service-state {  	 process {  		### check if there logfile server , if not create 1 		### also, read time of last event has been found file 		if ( [system.io.file]::exists("$logpath\$_.txt") ) {        			$lasttime = get-date (get-content "$logpath\$_.txt") }  		else {$lasttime = (get-date).adddays(-1) } 	    		 ### check events between last time found 1 , 		 $log = get-eventlog -logname system -computername $_ | ? {$_.timewritten -gt $lasttime -and $_.eventid -eq "6008"}  		  		 if ($log) { ### date , machinename of recent shutdown event 		  if( $log -is[array]){ 		 		$x =$log[0].timewritten 				$y = $log[0].machinename } 			else { 				$x =$log.timewritten 				$y = $log.machinename } 				 				$script:mailbody = $mailbody + "the system $y shutdown unexpectedly @ $x`n" 				 			  				set-content "$logpath\$y.txt" $x		 ### write time of event trhe logfile later 			}		 	} }  gc c:\serverlist.txt | service-state if ($mailbody) { send-mailmessage -to "abc@abc.com" -from "abc@abc.com" -subject "unexpected shutdowns" -body $mailbody -smtpserver "gateway_server" }

one thing though, find method in general bit slow on busy machines. have considered using event subscriptions this?

best regards, denniver



Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

2008 Windows Deployment Server Properties Error

Can no longer user MS Update - Files required to use Microsoft Update are no longer registered

How do a find data in one file, search for it in another file and if not found, write a custom message to another file