Windows PowerShell Get-Service

Windows PowerShell Scripting with Get-Service

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.

Topics for PowerShell Get-Service

 ♣

PowerShell Pre-requisites and Checklist

In the case of Windows 7 and later, you don’t need to download any extra files, just: ‘Add Feature’ –> Windows PowerShell.  However, for older operating systems, there are different versions of PowerShell for XP, Windows Server 2003 and Vista.  For such legacy systems only, you need to download PowerShell from Microsoft’s site.

Once you have installed PowerShell 2.0 or later, I recommend choosing the ISE (Integrated Scripting Engine) version, it will save buying a text editor.

Example 1: Listing All the Services on Your Computer

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).

# A simple command to list all Windows services
Get-Service

# If you need filter the list of services then try this:
Clear-Host
Get-Service -name Win*

Learning Points

Note 1: You can check the status, and startup values, for a named services thus:

# PowerShell Get-Service
Clear-Host
Get-Service Spooler

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:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Example 2: Manipulating the Output from Get-Service

Taking advantage of 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 -auto parameter produces more sensible column widths.

Note 5: 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:

Get-Service *  |Sort ServiceType | ft name, servicetype, status, canstop, -auto

Challenge 1: Research other properties, in particular more members of the Can* family.

Challenge 2: Try an alternative sort criterion, for example Sort-Object Status.

Note 6:  Out-GridView: PowerShell v 2.0 introduces a new cmdlet to control data display.  See more on how to pipe the results into out-GridView.

Example 3: Filtering the Output with ‘Where’

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-Object {$_.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".

Researching Get-Service and Other Family Members

Check Get-Service Parameters

# PowerShell Get-Service parameters
Clear-Host
Get-Help Get-Service -full

Remoting with PowerShell Service

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

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

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).

Real-life Tasks for Get-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!

Introducing If.. Else Logic to WMI Services

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’.

# Purpose: To check whether a service is installed
Clear-Host
$sName = "alerter"
$service = Get-Service -display $sName -ErrorAction SilentlyContinue
If ( -not $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: Remember, PowerShell is particular about brackets.

Note 11: Try "! $Service" instead of " -Not Service". In PowerShell and exclamation mark is an alias for -Not.

See more on PowerShell’s Else statement

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer’s Toolset v10

This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset now!

Download your fully functional trial copy of the Engineer’s Toolset v10

Our Missions for Get-Service

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.

More Members of the Service Family

 

# Research PowerShell's Service Cmdlets
Clear-Host
Get-Command -Noun Service

Get-Service: (Gsv) Useful for listing the services
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.

Summary of Windows PowerShell Get-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.

If you like this page then please share it with your friends

 


See more PowerShell examples of process and service

PowerShell Home   • Get-Process   • Stop-Process   • PowerShell Start-Process   • Set-Service

Get-Service   • Start-Service   • Stop-Service   • Restart-Service   • Free WMI Monitor

PowerShell Start-Sleep   • Get-WmiObject win32_service   • Windows PowerShell

Please email me 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.