Understanding PowerShell Objects

PowerShell is built around the concept of objects, not just text. This fundamental difference allows for structured data manipulation and powerful automation. Instead of parsing text output, you work with object properties and methods.

What are Objects?

In PowerShell, almost everything you interact with is an object. When you run a command like Get-Process, you don't just get a block of text; you get a collection of System.Diagnostics.Process objects. Each object has:

Working with Object Properties

You can access object properties using dot notation. For example, to get the Name property of the first process:

Example: Accessing Properties

(Get-Process)[0].Name

This command retrieves the first process object using Get-Process, accesses its Name property using .Name, and displays it.

Accessing Object Methods

Methods are invoked using parentheses, even if they don't require parameters.

Example: Using Methods

Get-Service -Name 'WinRM' | Stop-Service -Force

This example pipes a Service object to the Stop-Service cmdlet. While Stop-Service is a cmdlet that operates on objects, many objects have their own built-in methods. For instance, you might see methods like .Dispose() or .ToString().

Common Object Types

Here are some common object types you'll encounter:

Type Name Description Example Cmdlet
System.Diagnostics.Process Represents a running process on the system. Get-Process
System.ServiceProcess.ServiceController Represents a Windows service. Get-Service
System.IO.FileInfo / System.IO.DirectoryInfo Represents files and directories. Get-ChildItem
System.Net.NetworkInformation.IPAddress Represents an IP address. Get-NetIPAddress
Microsoft.PowerShell.Commands.MatchInfo Result of a regular expression match. Select-String

Inspecting Objects

To understand what properties and methods an object has, use the Get-Member cmdlet.

Example: Inspecting an Object

Get-Process -Name 'powershell' | Get-Member

This command shows all the properties (MemberType : Property) and methods (MemberType : Method) available for the powershell process object.

Note: Understanding objects is crucial for writing efficient and maintainable PowerShell scripts. Always try to work with objects rather than parsing text output whenever possible.

Object Properties vs. Cmdlet Parameters

While some cmdlet parameters might seem similar to object properties, they are distinct. Cmdlets operate on objects, and their parameters define how they manipulate or filter those objects. Object properties are inherent characteristics of the object itself.

Tip: You can select specific properties using Select-Object (aliased as select) and format the output using Format-Table (aliased as ft) or Format-List (aliased as fl).

Get-Process | Select-Object Name, CPU, WS | Format-Table -AutoSize