PSPowerShell · Lesson 5 of 8

Working with Objects

This is what makes PowerShell unique. Everything is an object. You don't parse text — you access properties. It's revolutionary if you're used to Bash.

PowerShell
# Get-Process returns Process objects (not text)
$proc = Get-Process -Name "pwsh"
$proc.Name          # pwsh
$proc.Id            # process ID
$proc.CPU           # CPU seconds
$proc.WorkingSet    # memory in bytes
$proc.StartTime     # datetime object

# Pipeline: get, filter, select, sort
Get-Process |
    Where-Object { $_.WorkingSet -gt 50MB } |
    Select-Object Name, Id, @{N="RAM(MB)"; E={[math]::Round($_.WorkingSet/1MB)}} |
    Sort-Object "RAM(MB)" -Descending |
    Format-Table

# Get-ChildItem — like ls/dir but returns FileInfo/DirectoryInfo objects
$files = Get-ChildItem -Path "C:Users$env:USERNAME" -Recurse -Filter "*.ps1"
$files | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }  # modified in last 7 days
$files | Measure-Object -Property Length -Sum  # total size

# Services
Get-Service | Where-Object { $_.Status -eq "Running" } | Measure-Object  # count running services

# Create custom objects
$servers = @(
    [PSCustomObject]@{ Name = "web01";  IP = "10.0.0.1"; CPU = 45 }
    [PSCustomObject]@{ Name = "db01";   IP = "10.0.0.2"; CPU = 72 }
    [PSCustomObject]@{ Name = "cache1"; IP = "10.0.0.3"; CPU = 12 }
)

$servers | Where-Object { $_.CPU -gt 50 } | Select-Object Name, CPU
$servers | Sort-Object CPU | Format-Table -AutoSize
◆ Note
Get-Member is your best friend in PowerShell. Pipe anything to Get-Member to see all its properties and methods: Get-Process | Get-Member. This works on any object and replaces reading documentation for basic exploration.