Email Sent When Service Stops - Question on Loops


so looking have email sent following stopping of service on given server, hoping powershell.  found great thread: http://social.technet.microsoft.com/forums/en-us/winservergen/thread/6ee23534-01ba-454b-b823-15fb243a51f7

this thread has great script:

while ((get-service "bits").status -eq"running") {start-sleep -seconds 60} send-mailmessage -from bits@ps.local -to admin@ps.local -body "bits stopped"-smtpserver server1

script works awesome. question is: can loop run indefinitely? realize scheduling might option, hoping have bit more streamlined that.  anyway, tried adding following variable:

$b = 1

do

{

while ((get-service "bits").status -eq"running") {start-sleep -seconds 60} send-mailmessage -from bits@ps.local -to admin@ps.local -body "bits stopped"-smtpserver server1

}

while ($b -eq 1)

but of course spammed inbox no end. have thought of trying build in restart-service/start-service cmdlets restart service, doesn't seem work.  idea?

maybe this:

$email = @{     = 'bits@ps.local'     = 'admin@ps.local'     smtpserver = 'server1' } while ($true) {     if ((get-service "bits").status -eq "stopped") {         send-mailmessage -from bits@ps.local -to admin@ps.local -body "bits stopped"-smtpserver server1          try {             start-service "bits" -erroraction,stop             $email.body = 'restarted bits service'             send-mailmessage @email         } catch {             $email.body = "unable start bits service! $_.exception.message"             send-mailmessage @email         }     }     start-sleep -seconds 60 }


boe prox
blog | poshwsus | poshpaig | poshchat



Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Error: 0x80073701 when trying to add Print Services Role in Windows 2012 Standard

Disconnecting from a Windows Server 2012 R2 file sharing session on a Windows 7,8,10 machine

Event ID 64,77,1008 Certificates Events Windows Server 2008, 2008R2