0

I need to Stop the service, and once the service is stopped i need to reboot the system. After the reboot i need to start the service if it is in stopped state using powershell script.

$stage= get-service -name "chrome"

if ( $stage.Status -eq "Running" )
{

Write-Host "The service " $stage.Name "is running"

Stop-Service -Name 'chrome'



}


if ( $stage.Status -eq "Stopped")

{
Restart-Computer -Wait

Start-Service 'chrome'


}
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
guhan v
  • 29
  • 4
  • 1
    Your script doesn't survive a reboot so you either have to run that script from another computer, make your chrome service automatic started or have a scheduled task at startup to start the chrome service. Far easiest is to set the chrome service to automatic in the service manager (what is the default anyway I believe?!) – Lieven Keersmaekers Nov 23 '18 at 07:25
  • @LievenKeersmaekers Is my condition is right? or i need to change it. because i need to validate it, once the chrome service is stopped then only i have to perform the restart – guhan v Nov 23 '18 at 07:28
  • Executing `Restart-Computer -Wait` on your own computer either fails or it ends the script at that point (I don't know, haven't tested it). Either way, in its current form, your `Start-Service 'chrome'` is never reached. Is there a problem setting the chrome service to automatic and have Windows take care of starting it on reboot? – Lieven Keersmaekers Nov 23 '18 at 07:43
  • @LievenKeersmaekers chrome is just a example service, am looking for other service. When i execute the script its just stopping the service its not moving to next step to reboot the machine – guhan v Nov 23 '18 at 07:53
  • Your `$stage` variable retains the (some) values of the service for the point in time you have assigned it. You'll need to either reassign the variable or just check it without using a variable – Lieven Keersmaekers Nov 23 '18 at 08:43
  • 1
    `Restart-Computer -Wait` doesn't work on the local computer (see my [answer here](https://stackoverflow.com/questions/53389934/remotely-reboot-computer-twice/) for explanation) – henrycarteruk Nov 23 '18 at 10:43
  • This should be possible when using Powershell Workflows. – bluuf Nov 23 '18 at 12:07

1 Answers1

0

You may need to run the code from different server to achieve your goal. as suggested above, once server rebooted, you can't resume back with the same script.

Other than that, there is small change needs to be done you script. which is, you need to call again below code between your if conditions. So that you will get a expected output

$stage= get-service -name "chrome"

Thameem J
  • 1
  • 1