11 April 2012

Restarting a service with powershell

It was one of those days. I realized that I've been doing the same small task over and over and so I thought: let's put that into a script. But then the writing of the scripts turns out to be a bit more complicated as expected. I should stop then and get on with my work, but nah, the challenge's there, I can't help it.

I should start writing all those little scripts down, just as a reference for later if I need it again but can't find it anymore. Let's do that now for one particular task.

What I needed to do: shutdown a service on a remote computer, copy some files on that remote computer from a remote computer (but only from the last added folder) and then start the service again. So I started with a bat file (windows, yes) but quickly discovered that determining the last added folder isn't that easy in a bat file. You can check whether a date is equal, but not if it's smaller or greater.

So let's try a powershell script for a change! I used to install software for that on XP, but now that I'm using Windows 7 that's not needed anymore, luckily.

Do not forget to set the execution policy, because default it is set to 'restricted' and I for one always forget on a new pc

    cmd
    powershell
    Set-ExecutionPolicy Unrestricted

After much googling I came up with this script:

&"sc.exe" \\192.168.1.yyy stop NameOfService
sleep -s 5
$from = "\\192.168.1.xxx\from\"
$to= "\\192.168.1.yyy\to\"
$a = Get-ChildItem $from| Where-Object {$_.PSIsContainer -eq $True} | sort -prop LastWriteTime | select -last 1
&robocopy "$from$a" $to*.* /S
&"sc.exe" \\192.168.21.yyy start NameOfService

Use sc to stop the service. Wait for 5 seconds because it can take a while before the service actually stops (should be a while-loop that checks the state perhaps, but 5 seconds was enough for me in all cases encountered). And then we have the power of powershell, we get all the folders sorted by last write time and select the last one, and the result of that is used in a robocopy call. At the end the service is started again.

God that was easy. I never go back to bat files again. It's only a matter of time and practice and I'll be writing them as quickly as a bat file.