This write-up will overview a guide to resolve the mentioned problem.
What are the “Select-Object” and “ExpandProperty” Properties in PowerShell?
The “Select-Object” cmdlet is utilized to select the objects and their properties from a collection of objects. While the “-ExpandProperty” is a “Select-Object” cmdlet’s switch that helps to get the details of the particular property.
Example 1: Display Property Values of an Object
This example will demonstrate the usage of “Select-Object” and “-ExpandProperty” cmdlets to select objects and properties from an array:
[pscustomobject]@{CarName='BMW';Color='Blue';Model='2023'}
[pscustomobject]@{CarName='Audi';Color='White';Model='2022'}
[pscustomobject]@{CarName='Honda';Color='Red';Model='2020'}
)
According to the above code:
- First, create an array of custom objects in PowerShell and assign it to a variable “$Car”.
- Inside an array, create three objects and add three properties inside each object.
- After that, assign the custom values to the defined properties:
Let’s select and display the object values in the output. For that reason, execute the given line of code:
According to the above code:
- First, add the array assigned variable “$Car”. After that, add the “|” pipeline to transfer the output from the “$Car” array to the “Select-Object” cmdlet.
- After that, use the “-ExpandProperty” cmdlet switch and assign the “CarName” property to get and display the values in the PowerShell console:
As it can be observed that the values have been displayed using the “Select-Object” and “-ExpandProperty”.
Example 2: Extract Services Name
This example will extract the last five services name using the “Get-Service” cmdlet:
In the above-stated code:
- First, add the “Get-Service” cmdlet and then use the “|” pipeline to pass the output to the “Select-Object” cmdlet.
- After that, use the “-ExpandProperty” switch command to select the particular value, which is “Name” followed by the “-Last” attribute, and define value “5” to display the name of the last five services:
It can be observed that the last five service names have been displayed on the PowerShell console.
Conclusion
The “Select-Object” cmdlet in PowerShell is used to select the properties from a collection of objects. While “-ExpandProperty” is the switch of the “Select-Object” cmdlet that is used to select the particular details of the object. This write-up will overview a complete procedural guide about the “Select-Object” and the “-ExpandProperty”.