CodeToLive

PowerShell Cmdlets & Pipelines

Cmdlets (pronounced "command-lets") are lightweight commands that implement specific functions in PowerShell, while pipelines allow you to chain commands together.

Cmdlet Structure

Cmdlets follow a consistent Verb-Noun naming pattern:

# Get all processes
Get-Process

# Stop a service
Stop-Service -Name "Spooler"

# Get system information
Get-ComputerInfo

Common Verbs

Verb Purpose Examples
Get Retrieve information Get-Process, Get-Service
Set Configure or change Set-Location, Set-Item
New Create new items New-Item, New-Object
Remove Delete items Remove-Item, Remove-Variable
Start Begin operations Start-Process, Start-Service
Stop End operations Stop-Process, Stop-Service

Parameter Types

# Positional parameters
Get-ChildItem "C:\Windows"

# Named parameters
Get-Service -Name "WinRM" -ComputerName "Server01"

# Switch parameters (flags)
Get-Process -IncludeUserName

# Parameter sets
Get-Help Get-ChildItem -Parameter *

Pipeline Basics

The pipeline (|) passes output from one cmdlet to another:

# Simple pipeline
Get-Process | Sort-Object CPU -Descending

# Filtering with Where-Object
Get-Service | Where-Object {$_.Status -eq "Running"}

# Selecting properties
Get-Process | Select-Object Name, CPU, Id

Pipeline ByValue vs ByPropertyName

# ByValue (accepts direct input)
"Hello" | Get-Member

# ByPropertyName (matches property names)
[PSCustomObject]@{Name="Notepad"} | Stop-Process

Common Pipeline Cmdlets

Cmdlet Purpose
Where-Object Filter objects
Select-Object Choose properties
Sort-Object Sort results
Group-Object Group by property
Measure-Object Calculate statistics
ForEach-Object Process each item

Advanced Pipeline Examples

# Multi-step pipeline
Get-Process |
  Where-Object {$_.CPU -gt 100} |
  Sort-Object CPU -Descending |
  Select-Object Name, CPU, Id |
  Export-Csv -Path "HighCPU.csv" -NoTypeInformation

# Using ForEach-Object
1..5 | ForEach-Object {
  "Processing number $_"
  Start-Sleep -Seconds 1
}

# Grouping and counting
Get-ChildItem -File | 
  Group-Object Extension | 
  Sort-Object Count -Descending |
  Select-Object Count, Name

Error Handling in Pipelines

# Continue on error
Get-ChildItem C:\, NoSuchDrive | Where-Object {$?}

# Error handling with Try/Catch
try {
  Get-Content "MissingFile.txt" -ErrorAction Stop
}
catch {
  Write-Warning "File not found: $_"
}

Performance Considerations

# Faster alternative to Where-Object
Get-Process | Where-Object CPU -gt 100

# Using .Where() method (PowerShell 4.0+)
(Get-Process).Where({$_.CPU -gt 100})