Slacker. Go ahead, say it. I know your thinking it. Work has been busy but that doesn't mean I'm slacking off on coding. Oh no, I'm hard at work writing new functions and subs. I finished one recently when I needed to stop and start a service on a remote machine. And as usual, I couldn't just make a sub that only stopped and started a service. I had to add in other abilities like Pause, Resume, and Restart. Oh yeah, now we're talking.
But that's not all. I started to think, what else would I want to do with a service? How about changing it's startup type to Automatic, Manual, or Disabled? That's something we network administrators need to do from time to time. So I added that in too.
I wrapped all the code up in a nifty little sub (sorry, no shiny paper and bow). To use it, simply pass the computer name, service name, and the action you want to complete and presto! The service will be changed.
chrip chrip chrip.. What's that? The little birdy on my shoulder said "what about errors?". Good point. What if we want to capture the return status of the action? For example, what if I try to start a service that is already started? It turns out that we can capture the return code. The code is a user un-friendly integer so run it through a select case and set a boolean variable as true/false as well as setting some status text. So now that we have that, how do we pass two variables back? You can't pass it back in a single function. So here's what I did.
To get the return code and status, declare these two variables in the main part of the script: blnServiceStatus and strServiceStatus.
When the action on the service completes, the return code is filtered and these two variables are set. All you need to do is declare them globally and now you've got the status! One special note on the blnServiceStatus results, I tried my best to interpret the return code as a true or false as representative of the success of the action. You may need to tweak these for your desired results.
All this talk and no action. Let's see some code!
And there you have it. A nice and robust sub for handling services. Remember, you can use this in a local script too. Just use "." as the computer name. :)