Our
tasks
for Windows services are to list them, to stop them, and especially to start them. I would like to begin
on this page with a thorough grounding in both the PowerShell syntax, and also the
properties available to
the Get-Service command. Once we have mastered the basics of this verb-noun pair, we will investigate tasks for other members of the 'Service' family;
for example, I have another page
on start-Service. To
digress into WMI, I have a separate page on
Get-WmiObject win32_service.
Download
PowerShell from Microsoft's site. One relevant point is that there are different versions
of PowerShell for XP, Windows Server 2003 and Vista. In the case of Windows 7 and Server
2008, you don't need a download, just 'Add Feature' Windows PowerShell.
Once you have installed PowerShell 2.0, I recommend choosing the
ISE (Integrated Scripting Engine) version, it
will save you buying a text editor.
Scripting Windows Services lends itself to one of my favorite techniques, namely having the GUI open while I execute the code. The advantage of this approach is two-fold; you can check what the script is doing
by observing how a value changes in the Services GUI. If you like this technique, click on the Windows Start button, Run, type services.msc
(do remember the .msc extension).
Get-Service
Learning Points
Note 1: You can check the status, and startup
values, for a named services thus:
Challenge: Try filtering with: Get-Service S* or use the square brackets and select a range:
Get-Service [r-w]*.
Note
2: I have
yet to find a PowerShell noun that is not singular, for example, Service (and not Services). Realization of this consistency saves me
making typos.
Note
3: PowerShell commands are not case
sensitive. Get-Service works as well as Get-Service.
Guy
Recommends: WMI Monitor and It's Free!
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems. Fortunately, Solarwinds
have created the
WMI Monitor so that you can examine these gems of
performance information for free. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.
Following research from Get-Service | Get-Member, we can refine the output so that we add extra properties, for example, CanStop and ServiceType. This example also illustrates how we can 'Sort' on ServiceType rather than the 'Name' property.
# PowerShell cmdlet to list Windows services Get-Service * | Sort-Object -property ServiceType ` | format-Table name, ServiceType, status, CanStop, -auto
Learning Points
Note 4: The tiny backtick` tells PowerShell that the same command continues on the next line. Without this symbol (`) there is no word-wrap, and thus PowerShell
would interpret the new line as a new command. In this instance we want one long command, which happens to spill over two lines.
Note
5: The -auto parameter produces more sensible column widths.
Note 6: When learning, I like to give the full syntax, however, for production scripts Sort-Object is normally abbreviated to plain 'Sort', just as format-Table is usually written as 'ft'. In
fact, you can also omit the -property parameter and the script will still work:
In a production network, I see numerous
opportunities for a short script to filter which services are running and which services have stopped. From a scripting point of view, this is a job for a 'Where' clause.
# PowerShell cmdlet to list services that are stopped
Get-Service * | where {$_.Status -eq "Stopped"}
Learning Points
Note 7: The 'Where' command crops up in many PowerShell scripts, therefore it is worth familiarizing yourself with the rhythm of the command:
Begin
the where clause with a
pipe '|'. Next open {Braces (not parenthesis)}, pay close attention to $_. These three symbols translate to 'this pipeline'. In the above example, I have chosen to filter the services based on the value of the property
'Status'. Remember that
PowerShell uses -eq and not the equals sign. Finally, we have the criterion: "Stopped", an alternative filter would be, "Running".
Challenge: Try changing "Stopped" to
"Running".
For your notebook: In other PowerShell scripts the structure of the 'Where' statement would be
the same, however, you would replace .Status with a property to suit your purpose. Each property has its own values which you would research, then substitute for "Stopped".
One aspect of remoting in PowerShell v 2.0 is simply to append
-computerName xyz to the command that you ran on the local machine.
For further research try:
Clear-Host Get-Command | where { $_.parameters.keys -contains
"ComputerName"}
Surprise! Get-Service is amongst the cmdlets that support
remoting, but stop, start and restart-Service are not on the list.
More bad news, stop, start and restart-Service really don't work on
network machines. Thus you have to employ different techniques
such as Get-WmiObject and InvokeMethod. Alternatively, you could
enter-PSSession and then run restart-Service as if you were on the local
machine. However, to get that working you have to first
install and setup WinRM
Get-Service Alias Gsv
With Microsoft, there are always at least
three ways of doing everything, what seems like redundancy when you are an
expert, seems like perspective when you are a beginner. One obvious
example is that you can abbreviate format-Table to ft. As you increase
your range of PowerShell commands, keep an eye out for another
PowerShell Alias, for example gci (Get-Childitem).
More Members of the Service Family
Clear-Host Get-Command -noun Service
Get-Service: (Gsv) Useful for listing
the services Set-Service: Crucial parameter -startuptype Start-Service: The verb 'start' says it all
Stop-Service: Handy for scripts which prevent unwanted services running e.g. Telnet Restart-Service: A nice touch by the creator's of PowerShell, no need to
explicitly stop then start the service.
It may seem that we are just bumbling about with these Windows Services,
however, if we are observant then we can gather useful knowledge, for
example Get-Service reveals that Window 7 no longer has the Alerter or
Messenger services. Also try: Get-Service WinRm, it will check whether
Windows Remoting has been installed.
What is even more instructive is the relationship between the properties
'DisplayName' and 'Name'. My point is that when it comes to scripting
you need to pay special attention of different values, for example try this:
Get-Service PRINT spooler |ft name, DisplayName.
Learn from my mistake,
I thought its name was Print Spooler, and its description was Spooler.
This was doubly wrong. The name is 'spooler', and for once there is no
description property!
Let us consider the possibility that the service is not installed; after all one, use of the
script is to check service availability. What we are going to do is introduce 'If ... Else' logic. The exclamation mark ! checks for a null value for the service name. Should this if
logic be true, then we declare ' This service is not installed on the computer', except we use a variable in place of 'This service'.
# PowerShell script # Purpose: To check whether a service is installed
Clear-Host $sName = "alerter" $service = Get-Service -display $sName -ErrorAction SilentlyContinue
if ( ! $service ) { $sName + " is not installed on this computer. `n Did you really mean: " + $sName } else { $sName + " is installed." $sName + "'s status is: " + $service.Status }
PowerShell Learning Points
Note 8: -ErrorAction SilentlyContinue. If a script encounters a runtime error it displays a helpful error message, then continues. This switch or
modifier merely suppresses that error message.
See more on
ErrorAction SilentlyContinue
Note 9: `n This grave accent (ASCII 096) followed by n tells the script to insert a carriage return.
Note
10: PowerShell is particular about brackets.
Note 11: Try "-not $Service" instead of "! Service". A
PowerShell exclamation mark is an alias for -not.
Guy Recommends: SolarWinds Engineer's Toolset v10
The Engineer's Toolset v10 provides a comprehensive console of utilities
for troubleshooting computer problems. Guy says it helps me
monitor what's occurring on the network, and the tools teach me more about how the system
itself operates.
There are so many good gadgets, it's like having free rein of a
sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.
Download your copy of the Engineer's Toolset v 10
One key role for a good computer techie is checking, starting, and sometimes stopping the operating system's services. Indeed, expertise with Windows Services is one discriminator between a real network administrator and a
'paper' MCSE impostor. The PowerShell scripts on this page will get you underway with my mission to monitor and control which Services should be running on your servers and
workstations.
Let us build-up logically. Firstly, we will list all the services on your computer. Next we will filter the script's output so that it lists only services which are "Stopped"
or "Running". From
there we will set about adjusting the start-up type to manual, automatic or disabled. Finally, we can create an advanced script, which will start or stop named
services.
Addendum: There is an alternative to the Get-Service cmdlet,
and that is to involve WMI and experiment with: Get-WmiObject win32_service.
Out-file
If I could digress and hark back to the verbosity of VBScript; because it took so much code to list the services, I feared that it would confuse beginners if I added another 10 lines of VBScript in order to output the list of services to
a text file. With PowerShell there is no such worry, all you need to store the results is to append these few words: | out-file "D:\PowerShell\Scripts\services.txt"
# PowerShell cmdlet to save services that are stopped to a file
Get-Service * |where {$_.Status -eq "Stopped"} ` | out-file "D:\PowerShell\Scripts\services.txt"
Note
12: As you can see, most of the command is taken up with the path
which specifies where you want to create the file; naturally you must amend this path to a location on your computer. Remember to add out-file to your notebook of invaluable PowerShell commands.
Members of the Service Family
Get-Service: Useful for listing
the services Set-Service:
Crucial parameter -startuptype
Start-Service: The verb 'start' says it all Stop-Service: Handy for
scripts which prevent unwanted services running e.g. Telnet Restart-Service: A nice
touch by the creator's of PowerShell; this cmdlet removes the need to
explicitly stop then start the service.
I declare that this page covers the basics of Get-Service. The examples explain how to list all the services, how to filter with a 'Where' clause, and
finally, for a permanent record, how to out-file. Next step: Start, Stop and Restart-Service.
See more PowerShell examples of process and service
Please write in if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems.
Fortunately, Solarwinds
have created the
WMI Monitor so that you can examine these gems of
performance information for free. Take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.