Select-Object (Alias: Select)
Last updated
Last updated
PowerShell provides powerful cmdlets like Select-Object
, Sort-Object
, and Group-Object
to manipulate and organize data in pipelines. These cmdlets allow you to filter, sort, and group objects based on specific properties, making it easier to work with large datasets.
The Select-Object
cmdlet is used to select specific properties or a subset of objects from a pipeline. It creates new objects with only the selected properties or objects.
Selecting Properties
To select specific properties of an object:
Expanding Properties
If a property is an array (e.g., Modules
in a process object), you can expand it to extract individual items:
Selecting First, Last, or Unique Items
First: Select the first n
objects.
Last: Select the last n
objects.
Unique: Select only unique items based on a property.
Examples:
The Select-String
cmdlet is used to search text using regular expressions, similar to grep
in Unix or findstr
in Windows.
Searching Files
To search for a pattern in files:
Searching Command Output
To search the output of a command:
Output of Select-String
Select-String
outputs objects with properties like:
Path: The file or input stream where the match was found.
LineNumber: The line number of the match.
Line: The matching line of text.
Example:
Quiet Mode
To return $true
if a match is found, or nothing otherwise:
The Sort-Object
cmdlet sorts objects based on one or more properties.
Sorting by Property
To sort objects by a specific property:
Sorting by Multiple Properties
To sort by multiple properties:
Named Calculated Properties
You can create custom properties for sorting or selecting:
The Group-Object
cmdlet groups objects based on one or more properties.
Grouping by Property
To group objects by a property:
Counting Items in Groups
To count items in each group: