We continuing our new series that answers common questions, or questions that have been asked about PowerShell. Today is all about Output To Console all services. What we intend to provide is one of the many, many ways you can accomplish these tasks within PowerShell.
All of the solutions are ours and demonstrate the author’s skill and ability level at the time of writing. That is to say, we might not always write the best PowerShell code. However, if you know of a better way we welcome that input.
Let’s start. Today’s question is:
I need to list all services running and not running on a device, how do I do this?
The Answer:
Within PowerShell Module Microsoft.PowerShell.Management
we have the Get-Service
cmdlet. This cmdlet gets the objects that represent the services on a computer. This includes all running and stopped services on the local machine by default.
If we type just Get-Service
inside a PowerShell console, you will return all services, their status, and their display name.
As you can see from the above screenshot this is not very clear. Everything is pushed together. What I am attempting to say is this is not ideal to read. As we know these are objects that are returned when we use Get-Service
let’s manipulate that a bit by piping |
the data to Sort-Object
.
PowerShell Pipeline – When commands are joined together in a pipeline. The output from one command is used as input for the next command in the pipeline.
Like this:
Get-Service | Sort-Object status
By piping |
the data from command Get-Service into Sort-Object we can now easily sort the service by Running and Stopped status. To take it a bit further and really customize the output, yet also stay to a one-line command I present you with my custom Get-Service
command.
Get-Service | Sort-Object Status | foreach-object {if ($_.Status -eq "stopped") { write-host -f red $_.DisplayName Service $_.Status } else { write-host -f green $_.DisplayName Service $_.Status }}
What exactly is that you are asking yourself?
The above command uses the Get-Service
cmdlet then sorts the output by Stopped and Running status. The command does this by piping |
the returned information from Get-Service into Sort-Object
. Afterward, the command then pipes |
that now sorted information into a Foreach-Object
so we can iterate through the entire list that was returned from our original Get-Service
command.
As we iterate through each line in the sorted output from the Get-Service
command the script writes the output per line to the console in red if the service is Stopped and green if the service is Running. The script also outputs to the console this information along with the DisplayName and Status.
The script is able to mark these red/green depending on their status. This is because inside the foreach we are using the PowerShell variable in the pipeline $_. .
What you get back is an ordered list of services in red for Stopped and green for Running.