PowerShell Objects
PowerShell is fundamentally an object-oriented automation framework. Unlike traditional command-line tools that output plain text, PowerShell commands (cmdlets) return objects that encapsulate data and methods. These objects form the backbone of PowerShell's pipeline, enabling dynamic, data-rich automation. Understanding how to work with PowerShell objects is essential for advanced scripting and administration tasks.
What Are PowerShell Objects?¶
PowerShell objects are instances of .NET classes or custom objects created in memory. They carry both data (properties) and behavior (methods). For example, the Get-Process cmdlet returns objects representing running processes, each with properties like Name, CPU, and Handles, and methods like Kill().
.NET Objects vs. PowerShell Custom Objects¶
PowerShell leverages the .NET Framework's object model, but it also allows you to create custom objects for specific tasks. The distinction matters when accessing properties and methods.
.NET Objects¶
These are instances of .NET classes (e.g., System.Diagnostics.Process). You access their properties and methods using dot notation or casting:
$process = Get-Process -Name "explorer"
$process.BasePriority # Access a property
$process.Kill() # Call a method
PowerShell Custom Objects¶
These are created using New-Object or the [pscustomobject] type accelerator. They are lightweight and ideal for ad-hoc data structures:
Accessing Properties and Methods¶
PowerShell provides multiple ways to interact with object properties and methods:
1. Dot Notation¶
2. Select-Object for Property Filtering¶
3. Get-Member to Discover Properties/Methods¶
The Pipeline and Object Flow¶
The PowerShell pipeline passes objects between cmdlets, enabling chained operations. Each cmdlet outputs objects that the next cmdlet processes:
Get-Processoutputs process objects.Where-Objectfilters objects based on their properties.Sort-Objectsorts objects by a property.
This flow allows complex logic without intermediate variables.
Key takeaways¶
- PowerShell objects combine data and methods, enabling rich automation.
- .NET objects are pre-defined classes, while custom objects are user-created for flexibility.
- Use dot notation,
Select-Object, orGet-Memberto explore and manipulate objects. - The pipeline passes objects between cmdlets, enabling seamless, data-driven workflows.