Select-Object

Using the PowerShell Cmdlet: Select-Object

Welcome back to Wahmans PowerShell blog! Today we’re diving into a powerful and versatile cmdlet in PowerShell: Select-Object. According to Microsoft Docs, this cmdlet “selects objects or object properties.” But what does that really mean?

In PowerShell, everything is an object. Whether you’re dealing with files, processes, or custom output, you’re typically manipulating objects. Select-Object helps you pick specific properties of those objects, or select a certain number of objects themselves. This can come in handy when filtering output, creating reports, or simplifying data for downstream processing.

Getting Started with Select-Object

Let’s start with some examples and increase the complexity as we go. These examples will illustrate why Select-Object should be in your PowerShell toolbox.

Example 1: Selecting Specific Properties from a Get-Process Output

Get-Process | Select-Object Name, Id, CPU

This simple example retrieves a list of running processes and selects just the Name, Id, and CPU properties. This is especially useful when you’re only interested in a subset of the available process information.

Example 2: Selecting the First N Objects

Get-Service | Select-Object -First 5

Need a quick look at just a few services? The -First parameter lets you grab only the first N items from the output. In this case, it grabs the first five services listed.

Example 3: Creating Custom Objects with Calculated Properties

Get-Process | Select-Object Name, @{Name="MemoryMB"; Expression={"{0:N2}" -f ($_.WorkingSet64 / 1MB)}}

Here, we’re using a calculated property using a hashtable. We define a new property MemoryMB, calculated by dividing the process’s working memory in bytes by 1 MB and formatting it to two decimals. This is incredibly useful when you’re customizing reports or dashboards.

Example 4: Deduplicating Output with -Unique

Get-EventLog -LogName System -Newest 100 | Select-Object Source -Unique

From a more advanced perspective, you can use -Unique to remove duplicate entries from your selection. This command grabs the latest 100 event log entries from the System log and outputs a distinct list of event sources.

Wrapping Up

Whether you’re just starting with PowerShell or want to build more complex scripts, Select-Object is a cmdlet that grows with your skills. It’s great for simplifying output, working with custom data, or optimizing your scripts to work more efficiently.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *