Working With Objects In Windows PowerShell

Everything in PowerShell is an object. Even a simple text is an object of type Strong. An object is a programmatic representation of anything. Each object has properties and methods.

Example - A Laptop

Properties of a Laptop include model name, OS, cost, screen size, and so on...

Methods of a Laptop are turn on laptop, shutdown laptop, restart laptop, and so on.


Using Get-Member Cmdlet, you can find the properties and methods of an object. You need to pipe the object to Get-Member to find out properties and methods of an object.


| symbol is the PowerShell Pipeline.


PS C:\> Get-Service | Get-Member

This will list all the properties and methods available for a service.

Windows PowerShell
Image: Properties and Methods of Service.


Using the New-Object Cmdlet, you can generate an object of any type. The choices for custom objects are Object and PSObject.

In this below example, let's create a new object using PSObject and store it in the laptopObject variable. Then, let's pipe this object to the Add-Member command. This Add-Member will add the properties or methods to the Object.
Next, we will use the MemberType of NoteProperty, and then give names to the properties Then finally, define the Value as whatever we need to.


The difference between Object and PSObjects is that Object creates an object of class System.Object, while PSObject creates an object of class System.Management.Automation.PSCustomObject].

Windows PowerShell
Image Create a New Object


We use Where-Object to filer and select particular property values from the collection of objects.


PS C:\ > $laptopObject | Where-Object {$_.OS -eq “OS X”}

This will return that object that has OS property value “OS X”

Windows PowerShell


Select-Object selects properties of an object or from set of objects.


PS C:\> $laptopObject | Select-Object -Property LaptopName,Model, Cost

Windows PowerShell


In Windows PowerShell, you can sort an object by -property parameter values. Let’s look at a simple example to understand how we can sort an object information.


PS C:\> Get-ChildItem C:\

This Cmdlet, return all the files and folders in My C: Drive

Windows PowerShell

Now, if you look at the highlighted part in the output, values of Length property are not sorted. So, in order to sort the Length property values, we use sort object. Below examples explain how to sort Length property values.


PS C:\ > Get-ChildItem C:\ | Sort-Object -Property Length

Windows PowerShell

Once I run the above Cmdlet, I can see that all the values of Length property are now sorted.