powershell.md
# PowerShell
Everything is an object on the pipeline. Cmdlets are named Verb-Noun.
## Navigation & files
```powershell
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
```powershell
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
```powershell
$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
```powershell
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
```powershell
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
```powershell
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
```powershell
Invoke-Command -ComputerName web01 { Get-Service }
Start-Job { Start-Sleep 5; "done" } | Receive-Job -Wait
```