Sunday, November 4, 2007

Basic Powershell #1 - Restarting a Remote Service

November 04, 2007 Posted by Jason Irwin , No comments
This latest lunchtime session was born out of necessity rather than thirst for knowledge. The client that I work for has many pcs and servers across a number of domains. A multitude of Operating Systems and (Software and Hardware) configurations often necessitates the use of a technology other than RDP to connect to PCs/Servers remotely. For this purpose we use Symantec PC Anywhere. Sometimes this is desirable – when connecting to a user’s pc it allows us to guide them through a particular process (in the same guise as remote assistance), sometimes not – when an RDP connection would do the job just as well and a little bit quicker.

A frustration I have with our outdated version of this software is that the host service on the remote machines tends to die at random or does not always restart after a reboot, meaning that boxes that I attempt to connect to are invariably in a random state – as often as not the host is down. There are 2 solutions I normally use:

1) Ask the user (if there is one and they have the appropriate permissions) at the other end to restart the host service.
2) Using Active Directory, restart the service yourself
a. Open Administrative Tools->Active Directory Users and Computers (installable on XP pro using the Windows Server 2003 Administration Pack)
b. Connect to the domain in question and search for the computer you are trying to connect to.
c. Right-Click and choose manage, allowing you to see and interact with the services on the remote box as you would those on your own PC.

The first solution is hit and miss, and can be a little frustrating (for the user as much as myself). The second solution is perfectly reasonable. But, managing the computer and listing the services thereon takes an extraordinary amount of time in my experience. Perhaps it is a peculiarity of the domains I connect to – but every single time (100%) I used this method, it proved extremely time consuming. This afternoon I was asked to connect to 10 PCs, and I figured there had to be another way. Leading to method #3: DIY.

I created a simple powershell script with 2 requirements:
1) It should allow a computer name or IP address to be entered
2) No credentials should be hard-coded. A PS1 file is a simple and un-compiled text file. My credentials should not be open to the public

The above is a complete code listing for said script. A computer name or ip address is input and the user is then prompted for their credentials. The input PC information is then piped into the ‘computer’ argument of a wmi call used to restart the service on the remote pc.