Lesson 5 of 8
Working with Objects
Learn to filter, sort and select objects in the . Because commands return objects, you read properties directly instead of parsing text.
# 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 -AutoSizeFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.