PowerShell #
Everything is an object on the pipeline. Cmdlets are named Verb-Noun.
Navigation & files #
Get-Location # pwd
Set-Location C:\src # cd
Get-ChildItem -Recurse -Filter *.log # ls/dir, recursive + filter
New-Item -ItemType Directory app # mkdir (File for a file)
Copy-Item a.txt bak\ -Recurse # cp -r
Remove-Item old -Recurse -Force # rm -rf (careful!)
Get-Content log.txt -Tail 20 -Wait # tail -f
The pipeline #
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
Get-Service | Where-Object Status -eq 'Running'
Get-ChildItem | ForEach-Object { $_.FullName } # $_ = current item
1..5 | Measure-Object -Sum # count / sum / average a stream
Variables, types & operators #
$name = "turtle"; $count = 42
$items = @(1, 2, 3) # array
$map = @{ id = 1; ok = $true } # hashtable
$env:PATH # environment variable
-eq -ne -gt -lt -like -match # comparison (NOT ==)
"$name has $($items.Count) items" # string interpolation
Flow & functions #
if ($count -gt 10) { "big" } else { "small" }
foreach ($i in $items) { $i * 2 }
function Get-Square([int]$n) { $n * $n }
Get-Square 9 # -> 81
Objects & formatting #
Get-Process | Get-Member # discover properties/methods
Get-Process | Format-Table Name, Id -AutoSize
Get-Content data.json | ConvertFrom-Json
[PSCustomObject]@{ Name = 't'; Age = 9 }
Help & discovery #
Get-Help Get-Process -Examples # usage with examples
Get-Command *item* # find cmdlets by pattern
Get-Alias ls # what an alias maps to
Remoting & jobs #
Invoke-Command -ComputerName web01 { Get-Service }
Start-Job { Start-Sleep 5; "done" } | Receive-Job -Wait
Error handling #
try {
Get-Content missing.txt -ErrorAction Stop # force a terminating error
} catch {
Write-Warning $_.Exception.Message # $_ = the error record
} finally {
"cleanup runs either way"
}
$ErrorActionPreference = 'Stop' # make errors terminating, script-wide
Most cmdlet errors are non-terminating, so
catchnever sees them. Add-ErrorAction Stop(or set the preference) to make them catchable.
Searching & splatting #
Select-String -Path *.log -Pattern 'ERROR' # grep across files
Test-Path C:\src\app.config # exists? -> $true / $false
$params = @{ Path = 'C:\src'; Recurse = $true; Filter = '*.cs' }
Get-ChildItem @params # splat a hashtable as args
Data in & out #
Get-Process | Select-Object Name, Id | ConvertTo-Json
Import-Csv users.csv | Where-Object { $_.Active -eq 'true' }
Get-ChildItem | Export-Csv files.csv -NoTypeInformation