BudiBadu Logo
Samplebadu

PowerShell by Example: Objects

PowerShell 7

Working with .NET objects and custom objects through this sample code demonstrating PSCustomObject creation, Add-Member for dynamic properties, Select-Object with calculated properties, Get-Member for object inspection, and property access methods.

Code

# Create a custom object
$obj = [PSCustomObject]@{
    Name = "Server01"
    Status = "Online"
}

# Add a new property dynamically
$obj | Add-Member -MemberType NoteProperty -Name "IP" -Value "192.168.1.10"

# Calculated properties with Select-Object
$processInfo = Get-Process | Select-Object Name, CPU, @{
    Name = "MemoryMB"
    Expression = { $_.WorkingSet / 1MB }
} | Select-Object -First 5

# Inspect object members
$obj | Get-Member

# Display formatted table
$processInfo | Format-Table -AutoSize

Explanation

PowerShell treats everything as objects, from simple strings and numbers to complex data structures and cmdlet outputs. Objects consist of properties (data fields storing information), methods (functions the object can perform), and a type (defining the object's .NET class). The [PSCustomObject] type accelerator provides the most efficient way to create custom objects from hashtables, generating lightweight objects with ordered properties.

The Add-Member cmdlet dynamically attaches properties or methods to existing object instances. Member types include NoteProperty for simple properties, ScriptProperty for calculated properties, ScriptMethod for methods, and AliasProperty for property aliases. This dynamic member addition is useful when aggregating data from multiple sources or enhancing objects with computed values.

Calculated properties in Select-Object transform object data using hashtables with Name (or Label) and Expression keys. The expression is a script block that computes the new property value, often performing mathematical operations, string manipulations, or property combinations. The Get-Member cmdlet reveals an object's type, properties, and methods, essential for discovering available object capabilities and understanding pipeline data structures.

Code Breakdown

2
[PSCustomObject]@{} creates lightweight custom object from hashtable.
8
Add-Member dynamically adds property to existing object instance.
11-13
@{Name=...; Expression={}} defines calculated property with script block.
17
Get-Member displays object type, properties, and methods.