PowerShell Basics Level: Beginner Chapter 4: Everyday Commands That Save Hours
Select-Object, Where-Object, and Sort-Object
These three cmdlets shape a result: Select picks properties, Where keeps matching objects, and Sort orders them. Used together, they answer most "show me" questions.
Lesson 1 of 4 in Chapter 4: Everyday Commands That Save Hours. Previous step in this path: The Filter parameter. 3 learning objectives, 8 examples, and a knowledge check.
Start: what you will learn
These three cmdlets shape a result: Select picks properties, Where keeps matching objects, and Sort orders them. Used together, they answer most "show me" questions.
Learning objectives
- Pick properties with Select-Object
- Filter objects with Where-Object
- Sort results with Sort-Object, including descending order
Concept in simple words
What it is: Select-Object, Where-Object, and Sort-Object are three shaping commands. Select-Object picks which facts, called properties, you want to see. Where-Object keeps only the items that pass a test you write. Sort-Object puts the items that remain into order by a property you choose. Together they turn a long, noisy list into a short answer.
Why it works
Why you need it: a plain Get command is honest, but it is often too much. It can show every property, every row, and in an order that does not help you. You do not need to read all of that. You need to ask a clear question, such as which services are stopped, or which processes use the most CPU, and then let PowerShell cut the list down to that answer.
What PowerShell is doing behind the command: PowerShell passes objects, not just text, from one command to the next. Think of an object as a small record with labelled fields. A service object has a Name field, a Status field, and a DisplayName field, all kept together. Because the fields stay labelled, the next command can check a field, drop a field, or sort by a field without guessing from the text on screen. That is why filtering and sorting stay reliable, even when the list is long.
Think of it like this
Think of it like this: imagine a box of index cards for every service on a computer. Select-Object is choosing which lines on each card you want to read. Where-Object is keeping only the cards that match your rule, and putting the rest back in the box. Sort-Object is laying the kept cards out in order, for example by name or by size. If you mix up the jobs, you get the wrong pile, so keep each job clear in your mind.
How it works, step by step
How it works, step by step: first, get your items with a Get command. Next, filter them with Where-Object, and inside its braces use $_ to mean the current item, plus a comparison such as -eq for equals or -gt for greater than. Then sort what is left with Sort-Object, adding -Descending if you want largest or latest first. Finally, use Select-Object to keep only the properties you want to show, and add -First with a number if you only want the top few. The short version is get, filter, sort, then select.
What $_ really means: in Where-Object { $_.Status -eq "Stopped" }, the braces hold a small test, called a script block. PowerShell runs that test once for each item. Each time it runs, $_ stands for the one item being tested right now. It is not the whole list, and it is not a fixed name. It changes as PowerShell walks through the list, one item at a time. If you write the test without $_, PowerShell has nothing to compare, so the test cannot work as you intended.
The comparison operators you will use most: -eq means equals, -ne means not equals, -gt means greater than, -ge means greater than or equal to, -lt means less than, and -le means less than or equal to. For text patterns, -like uses simple wildcards, where * means any characters, so "S*" means a name that starts with S. -notlike is the opposite. -match uses a more powerful pattern called a regular expression, and it is best kept for patterns you already understand, because a small pattern mistake can match far more than you expected. For text, the usual comparison operators ignore the difference between upper case and lower case, so "running" and "Running" count as equal in a simple -eq test.
How to combine tests: use -and when every part must be true, and -or when any part may be true. For example, $_.Status -eq "Running" -and $_.Name -like "S*" keeps only running services whose names start with S. Use -not to reverse a test, but keep it simple. If a combined test gets hard to read, split it into two Where-Object steps, or check each part on its own first. A test you can read is a test you can trust.
A shorter form of Where-Object: you can also write Where-Object Status -eq "Stopped", without braces and without $_. This shorter form works for one simple comparison, and it is handy for quick checks. The longer brace form is still the one to learn well, because it can hold -and, -or, and more complex tests. If the shorter form ever confuses you, go back to the brace form and spell the test out in full.
Select-Object in depth: by default, Select-Object keeps the properties you name, in the order you name them. Select-Object Name, Status shows Name first and Status second, even if the original object listed them the other way round. You can name one property, several properties separated by commas, or * to mean all properties. Selecting * is useful when you want to see everything for a quick check, but it defeats the purpose of trimming the display, so use it only for a small result.
Select-Object can also pick rows, not just columns. -First 5 keeps the first five items, -Last 5 keeps the last five items, and -Skip 5 drops the first five items and keeps the rest. -SkipLast drops items from the end. -Unique keeps only one copy of each identical result, which is handy when the same name appears many times. A useful pattern is to sort first, then use -First, because then "first" means the top of your chosen order, not just whatever order the items happened to arrive in.
Two more Select-Object tools, used with care: -ExpandProperty takes one property and returns its value on its own, instead of an object with that property inside it. That is useful when you want a plain list of names, but it means later steps no longer have the other properties to work with. -ExcludeProperty removes named properties, but it only works when you also name properties with -Property, so Select-Object * -ExcludeProperty StartTime means all properties except StartTime. If -ExcludeProperty seems to do nothing, check that you also used -Property.
Calculated properties, explained simply: sometimes the property you want does not exist yet. You can build it with a small hashtable of the form @{ Name = "MemoryMB"; Expression = { $_.WorkingSet64 / 1MB } }. Name is the label for the new column, and Expression is the calculation for each item, again using $_ for the current item. In the example, WorkingSet64 is the memory used by a process in bytes, and dividing by 1MB turns it into megabytes. This does not change the original object, it only adds a new column for display in that one command.
Sort-Object in depth: without extra words, Sort-Object sorts in ascending order, which means smallest first for numbers, A to Z for text, and oldest first for dates. Add -Descending to reverse it, so largest, Z to A, or newest comes first. You can sort by more than one property, for example Sort-Object Status, Name, which groups by Status first and then orders by Name inside each group. Sorting by several properties is often clearer than sorting by one property and hoping the rest falls into place.
What kind of value you sort matters: numbers sort by value, so 2 comes before 10. Text sorts letter by letter, so "10" comes before "2", because the first character 1 comes before 2. Dates sort by time, not by how the date looks as text. If a sort looks wrong, do not blame the sort first. Check what kind of value is in the property. A number stored as text is the most common cause of a strange order, and the fix is to sort by a true number property, or to convert the value before you sort.
How the pipeline flows through these three commands: Where-Object can pass each item on as soon as it passes the test, one at a time. Sort-Object cannot do that, because it cannot know which item is first until it has seen them all, so it collects the items, sorts them, and only then passes them on. That is normal, but it means sorting a very large list takes a little longer and uses more memory than filtering alone. If a command feels slow, sorting a huge unsorted list is one place to look, and filtering first helps, because sorting fewer items is faster.
Let us walk through an example: in Get-Service | Where-Object { $_.Status -eq "Stopped" } | Select-Object Name, the first part gets service objects. The middle part checks each service in turn, and $_ is the service being checked right now, so only stopped services pass through. The last part keeps only the Name property for display. Look at the output and check that every row really is stopped, and that no extra columns distract you. If the output is empty, that is also information. It may mean no services are stopped, or it may mean your test has a spelling mistake, so check both before you conclude anything.
When to use it
When to use it, and when not to: use these three commands whenever a plain Get command gives you too much, too many rows, or the wrong order. They are perfect for questions like which services are stopped, or which processes use the most CPU. Do not use Select-Object before Where-Object if your test needs a property you are about to drop, because that property will be gone. Filter first, sort next, and select last. Also, do not sort before you filter when you only need a few rows, because sorting the whole list first is wasted work.
Worked examples
Read each example in order. Each one explains its parts, then shows what to look for in the output.
Syntax
Get-Command | Where-Object { <test> } | Sort-Object <property> | Select-Object <properties>Example 1
Sorts by CPU, largest first, then keeps the top three rows with two properties. CPU is the total processor time used by the process. Look for the largest value at the top, and check that only three rows appear.
Get-Process | Sort-Object CPU -Descending | Select-Object Name, CPU -First 3Illustrative output: Name CPU ---- --- pwsh 12.5
Example 2
Filters first, then picks one property. Filtering early keeps the work small. $_ is the current service, Status is the property being tested, and -eq means equals. Look for only stopped services in the result.
Get-Service | Where-Object { $_.Status -eq "Stopped" } | Select-Object NameIllustrative output: Name ---- Spooler
Example 3
Get-Service gets service objects. Where-Object keeps only services whose Status property equals Running, with $_ meaning the current service. Sort-Object Name puts the kept services in name order. Select-Object keeps only Name and Status, and -First 5 keeps the first five rows, so the result is short and easy to read.
Get-Service | Where-Object { $_.Status -eq "Running" } | Sort-Object Name | Select-Object Name, Status -First 5Illustrative output: Name Status ---- ------ Spooler Running
Example 4
This is the shorter Where-Object form, with no braces and no $_. It does the same single test as the brace form: keep services whose Status equals Stopped. Use this form for quick checks, and use the brace form when you need -and, -or, or a more complex test.
Get-Service | Where-Object Status -eq "Stopped" | Select-Object Name, StatusIllustrative output: Name Status ---- ------ Spooler Stopped
Example 5
Where-Object now has two tests joined by -and, so both must be true. The first test checks Status, the second checks whether Name matches the pattern S*, where * means any characters after S. Sort-Object Name orders the survivors by name. Look for only running services whose names start with S, and check that a stopped service starting with S is not in the list.
Get-Service | Where-Object { $_.Status -eq "Running" -and $_.Name -like "S*" } | Sort-Object Name | Select-Object Name, StatusIllustrative output: Name Status ---- ------ Spooler Running
Example 6
Sort-Object CPU with no -Descending sorts smallest first. -Last 3 then keeps the three items at the end, which are the three largest CPU values, still in ascending order among themselves. If you expected largest first, add -Descending and use -First 3 instead. Compare the two forms and notice how the same three rows appear in opposite order.
Get-Process | Sort-Object CPU | Select-Object Name, CPU -Last 3Illustrative output: Name CPU ---- --- pwsh 12.5
Example 7
Select-Object keeps Name and adds a new column called MemoryMB. Inside the Expression, $_ is the current process, WorkingSet64 is its memory use in bytes, dividing by 1MB converts bytes to megabytes, and [math]::Round rounds the result to one decimal place. Look for the new MemoryMB column, and check that the numbers are far smaller than raw byte counts, which is a sign the conversion worked.
Get-Process | Select-Object Name, @{ Name = "MemoryMB"; Expression = { [math]::Round($_.WorkingSet64 / 1MB, 1) } } -First 3Illustrative output: Name MemoryMB ---- -------- pwsh 45.2
Example 8
-ExpandProperty Name returns the name values on their own, as plain text values, not as objects with a Name property. That is handy for a simple list, but later steps can no longer use Status or DisplayName, because those properties are gone. Look for a plain list with no column header row for Name.
Get-Service | Select-Object -ExpandProperty Name -First 3Illustrative output: Spooler
Nothing on this page executes PowerShell code. The outputs above are illustrative only.
Common mistakes and troubleshooting
Read these before you try the examples, so you can spot the same problems in your own work.
- Writing Where-Object without $_, so the test has nothing to compare.
- Selecting properties before filtering, which can remove the property your filter needs. Filter first, select last.
- Sorting a property that holds numbers as text, so the order comes out alphabetically and 10 appears before 2. If a sort looks wrong, check whether the values are text or numbers before you trust the order.
- Using = instead of -eq in a test. In PowerShell, = stores a value in a variable, it does not test equality, so a test written with = will not filter the way you expect. Always use -eq for equals in a Where-Object test.
- Forgetting quotes around a text value, for example writing -eq Stopped instead of -eq "Stopped". Without quotes, PowerShell treats Stopped as a command or variable name, not as text, and the test fails or behaves strangely.
- Using -like without a wildcard, for example -like "Spool" when you meant names starting with S. Without *, -like behaves like an exact match, so add * where you mean any characters, as in "S*".
- Spelling a property name wrong in Select-Object. PowerShell does not always stop you, it may show an empty column instead, which looks like missing data. If a column is blank, check the spelling against the real property name first.
- Sorting, then using -First, and forgetting that the default sort is ascending. Sort-Object CPU | Select-Object -First 3 gives the three smallest values, not the three largest. Add -Descending when you want the largest first.
Knowledge check
Knowledge check
Which order is usually best for get, filter, sort, and select?
Pick one answer. Feedback appears right away, and you can try again.
Remember this and next step
Remember this: get, filter, sort, then select. Keep that order in mind and most shaping jobs will fall into place. If a result looks empty, check your test and check that you did not drop the property your test needs. If a result looks wrongly ordered, check whether the values are numbers or text. If a result is too long, add -First and ask yourself whether you really need every row, or just the top few.
Next step: Verbose, WhatIf, and Confirm