cosine83

Restart Service with E-mail

Sep 19th, 2014
527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $Server = "testPC"
  2. $SMTP = "mail.test.com"
  3. $Date = Get-Date -format "MM.dd.yyy HH:mm"
  4. $Stopped = $false
  5. $LogExists = $false
  6.  
  7. If ($LogExists) {
  8.     Try {
  9.         New-EventLog -LogName Application -Source "Scheduled Task" -ErrorAction SilentlyContinue
  10.         $LogExists = $true
  11.     }
  12.     Catch {
  13.         Return $null
  14.         $LogExists = $true
  15.     }
  16. }
  17. If (!$LogExists) {
  18.     Write-Host "Event log already exists"
  19. }
  20. If ($Stopped) {
  21.     Try {
  22.         $Stop = Get-Service -ComputerName $Server -Name Test | Set-Service -Status Stopped -Verbose -ErrorAction Stop
  23.         Write-EventLog -LogName Application -Source "Scheduled Task" -EntryType Information -EventID 1337 -Message "Successfully stopped the Test service."
  24.         $Stopped = $true
  25.     }
  26.     Catch {
  27.         Write-EventLog -LogName Application -Source "Scheduled Task" -EntryType Error -EventID 1337 -Message "Failed to stop the Test service."
  28.         Send-MailMessage -SmtpServer $SMTP -From $From -To $To -Subject "Scheduled Task" -Body "Failed to stop the Test service on $Date!"
  29.         Break
  30.     }
  31. }
  32. If (!$Stopped)
  33. {
  34.     Try {
  35.         $Start = Get-Service -ComputerName $Server -Name Test | Set-Service -Status Running -Verbose -ErrorAction Stop
  36.         Write-EventLog -LogName Application -Source "Scheduled Task" -EntryType Information -EventID 1337 -Message "Successfully restarted the Test service."
  37.         Send-MailMessage -SmtpServer $SMTP -From $From -To $To -Subject "Scheduled Task" -Body "The scheduled task completed and restarted the Test Service Successfully on $Date!"
  38.     }
  39.     Catch {
  40.         Write-EventLog -LogName Application -Source "WFTD Scheduled Task" -EntryType Error -EventID 1337 -Message "Failed to start theTest service."
  41.         Send-MailMessage -SmtpServer $SMTP -From $From -To $To -Subject "Scheduled Task" -Body "Failed to start the Test Service on $Date!"
  42.         Break
  43.     }
  44. }
  45. Else {
  46.     Send-MailMessage -SmtpServer $SMTP -From $From -To $To -Subject "Scheduled Task" -Body "The scheduled task completed but ran into errors on $Date!"
  47. }
Advertisement
Add Comment
Please, Sign In to add comment