Powershell – How to systematically shut down Windows services in order

automationpowershellservicewindows-server-2008

We have this open source application that has three (3) services. For the purpose of this question, let's call them A, B, and C.

Now, they have to be shut down in a specific order. That order would be A then B then C.

If B shuts down before A then we run into all kinds of problems. Same is true if C shuts down before B or A. Plus, each service can take a different amount of time to shut down due to how many users were using it.

Oh, this need to be wrapped up in a DOS batch file or something a non-techy user could just double-click to initiate. (PowerShell is not out of the question but I've never used it). Also, I'm a C# coder so that could be used too.

Anyway, when the restart is initiated the following needs to happen:

1) Initiate shutdown of service A
2) When service A is down, it should trigger the shutdown of service B
3) When service B is down, it should trigger the shutdown of service C
4) When service C is down, it should trigger the START UP of service A
5) When service A is UP, it should trigger the START UP of service B
6) When service B is UP, it should trigger the START UP of service C

So as you can see, each stop/start needs to wait on the previous to be completely finished before moving on. And since each service can take a few seconds to a few minutes, we can't use any kind of timing tricks.

Suggestions greatly appreciated.

Thanks!

Best Answer

You could do this using PowerShell. To stop a service, you use the Stop-Service command. Starting a service is with the Start-Service command. So, you could create a script that had a few entries like the following for each service you need to stop, in order:

Stop-Service ServiceA
do { Start-Sleep -Milliseconds 200}
until ((get-service ServiceA).status -eq 'Stopped')

and to start the services:

Start-Service ServiceA
do { Start-Sleep -Milliseconds 200}
until ((get-service ServiceA).status -eq 'Running')

You could then string 6 of those code blocks together in a script, save it as a .ps1 file, and run it from the powershell prompt as so:

PS C:\> C:\Path\To\Script\script.ps1