Link to home
Start Free TrialLog in
Avatar of Mike Bishop
Mike BishopFlag for United States of America

asked on

Powershell script to stop service, wait until it's stopped, start the service, wait until it's running then continue

I'm new to Powershell scripting and am trying to write a script that perform the following steps:

1. Stop the service on a remote computer (Service is VWServicePE, Computer is Computer1 in this example)
2. Wait for the service to stop before continuing
3. Continue once it's confirmed to be stopped
4. Start the service on the remote computer
5. Wait for the service to start before continuing
6. Continue once it's confirmed to be running

What I have below works to stop and start the service but the looping is not right as far as it waiting for the service to stop/start before proceeding.  Can anyone offer recommendations?

$state0 = "Stopped"
$state1 = "Running"
$svc1 = Get-Service -Name VWServicesPE -ComputerName Computer1

$svc1 | Set-Service -Status $state0
do {$svc1.Status}
Until ($svc1.Status -eq $state0)

$svc1 | Set-Service -Status $state1
do {$svc1.Status}
Until ($svc1.Status -eq $state1)
Avatar of becraig
becraig
Flag of United States of America image

This might work, I think you could go about this better though.

$state0 = "Stopped"
$state1 = "Running"
$svc1 = Get-Service -Name WSService -ComputerName Computer1
$svc1 | Set-Service -Status $state0
while($svc1.Status -ne  $state0) { $svc1.Status }

Open in new window

SOLUTION
Avatar of Albert Widjaja
Albert Widjaja
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you can also change the input type from the above default list of server into some members of certain OU with the following changes:

replace the following line
$serverlist = get-content "$path\ServerList.txt"

with
$serverlist = Get-QADComputer -SearchRoot 'domain.com/Custom Servers OU' -OSName "Windows*Server*" -ShowProgress -Activity
I just realized I pasted in the wrong thing but it looks like ITStystemEngineer's should work just as well.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the suggestion as well BECraig ;-)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mike Bishop

ASKER

Working through these now and will come back with a response.  Thanks for all of the input.