Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Powershell script to stop service, start service - scheduled task

$
0
0

I am trying to get this script to work on a windows 2008 R2 server to stop a service for example "spooler", then start the service.

I want to get an email only if the task fails, but right now for testing I'm trying to get it to send an email when the task runs.  So far I can't get the task to run at all, the service doesn't stop, I am not sure where I should be putting the variable for the service name, and then for the email, I thought there was an easier way to do this, but I tried and couldn't get it to work, so I copied the email portion from another script I found online, but the email doesn't work either.  

## Reference to System.Net for email alerts
[void][System.Reflection.Assembly]::LoadWithPartialName(“System.Net.Mail”)

function restart-service
{
param ($srvName)

## stop service
stop-Service $srvName
$service = get-service $srvName

if($service.status -ne “Stopped”)
{
email-admin($srvName + ” has failed to stop, please manually stop and restart.”)
write($srvName + ” has failed to stop, please manually start.”)
}

##start service
start-Service $srvname
$service = get-service $srvName
if($service.status -ne “Running”)
{
email-admin($srvName + ” has failed to start, please manually start.”)
write($srvName + ” has failed to start, please manually start.”)
}
else
{
write($srvName + ” has started.”)
}
}

##email if failed
function email-admin($body)
{
$mail = New-Object System.Net.Mail.MailMessage
$mail.From = “psScript@server”
$mail.To.Add(“your@email.com”)
$mail.Subject = “Service Restart”
$mail.Body = $body
$smtp = New-Object System.Net.Mail.SmtpClient(“your.smtp.com”)
$smtp.Send($mail)
}

restart-service BITS
[/ps]

I put this into the task scheduler:

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -nolog -command “&{c:\Scripts\restartService.ps1}”




Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>