When Things Go Wrong
Read red text calmly, handle errors in a script, choose where output goes, and step through a script line by line.
Updated
Errors
- Reading Errors, and `-ErrorAction` (Apprentice): PowerShell's red text names the command that failed, what went wrong and, in a script, the file and line; some errors stop a command and some let it carry on, -ErrorAction decides what happens next, and $Error keeps a list of them.
- `try`, `catch` and `finally` (Journeyman): try runs your lines, catch runs only if one of them hits an error that stops it (which -ErrorAction Stop arranges), $_ in catch is the error, so you can tell the user what happened and what to do, and finally runs whatever happens.
Output
- Where Output Goes: `Write-Output`, `Write-Host` and Friends (Journeyman): Write-Output sends a script's results down the pipeline, where the next command, a variable or a > file receives them, while Write-Host, Write-Warning, Write-Verbose and Write-Error send words for people to the screen, each on a channel of its own that > and the pipeline leave alone.
Debugging
- Debugging in VS Code (Journeyman): A breakpoint pauses a script on a line in VS Code, so you can look at every variable, step through it one line at a time with F10, and watch an expression until a value surprises you; Set-PSBreakpoint does the same at the prompt.
Exercise: Make It Fail Well
- Exercise: Make It Fail Well (Journeyman): Fix a photo mover that loses photos on a bad day, so a failed copy never deletes a photo, a photo with the same name is never replaced, its results stay apart from its messages and a summary prints whatever happens, then answer four questions on reading errors and debugging while a Pester check tries it for real.