Wednesday 26 March 2014

Working with Windows Services in Powershell

We can use the get-wmiobject method in order to retrieve properties of windows services on local or remote servers.

The query below is an example on how to get the properties of the Print Spooler service on a local machine (ie. the same machine that the script is being executed on)

To get the "Service Name" of a windows service, go to services.msc, select a service, open it's properties (right click > Properties) and look at the "Service Name" at the top. 

$serviceprops = get-wmiobject -class win32_service -filter "name='Spooler'"

If we then run $serviceprops we get the following information;

ExitCode  : 0
Name      : Spooler
ProcessId : 1628
StartMode : Auto
State     : Running

Status    : OK

This information could therefore be used to check the respective windows process ID, start mode, state and status of a service

The query below is an example on how to get the properties of the Print Spooler service on a remote machine (server1)

$serviceprops = get-wmiobject -computername "server1" -class win32_service -filter "name='Spooler'"

As you can see, the command is mostly the same, we have simply added the argument "-computername "server1"" to make the get-wmiobject query run on the remote server.

We can then take this one step further and perform an action (aka method) on a service, such as starting or stopping it. To view the available methods for the service, run a get-member on the $serviceprops variable;

$serviceprops | get-member

You will then see a list of available methods (and properties) for the variable.

Two of the most common methods for a service would be to start or stop the service. We simply append the respective methods onto the end of the $serviceprops variable (after it has run the get-wmiobject query above to get the service properties).

To start a service;
$serviceprops.startservice()

To stop a service;
$serviceprops.stopservice()

No comments:

Post a Comment