Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Schedule restart of service & email

$
0
0

I suspect that part of your problem is that your code isn’t waiting for the service to stop before testing if it has stopped

for testing purposes I’d break this down into a number of sections. I’d start with the code to stop and start the service. You can use something like this:


$srvname = "BITS"

if ( (Get-Service -Name $srvname).Status -eq 'Running'){
Stop-Service -Name $srvname
}
else {
## may want to send email to this effect
Write-Warning "$srvname service NOT running"

## use a break if you want to stop here otherwise comment out
break
}

while($true){
if ( (Get-Service -Name $srvname).Status -eq 'Stopped'){
## replace Write-Host by email function
Write-Host "$srvname STOPPED"

#this next line is just for testing - remove in production
Get-Service -Name $srvname
break
}
}
Start-Service -Name $srvname
while($true){
if ( (Get-Service -Name $srvname).Status -eq 'Running'){
## replace Write-Host by email function
Write-Host "$srvname Running"
break
}
}

Some services can’t be stopped which I haven’t handled here – check the CanStop property returned by get-service

Once you have the service management section sorted you can test email part. You’re using Windows 2008R2 which has PowerShell 2.0 which has a send-mailmessage cmdlet. Check that out rather than writing your own function.

The final part of the problem is that you are running this as a scheduled task. Make sure that the task runs under a security context that can stop/start services & send email. The task needs to be set to run without the user logged on if you want it to be running unattended

Hope this helps – please bring any further questions back to this thread


Viewing all articles
Browse latest Browse all 13067

Trending Articles