Input and Decisions

Give a script parameters, ask a question, and make it choose with if and switch.

Updated

Input

  1. Parameters: `param()` (Apprentice): A param() block at the top of a script names its inputs, so one script works on any folder; each parameter can have a type, a default value or be a [switch], Mandatory makes PowerShell ask for a missing one, and Tab completes their names.
  2. Asking Questions: `Read-Host` (Apprentice): Read-Host asks a question, waits, and hands back what was typed, always as text, -MaskInput shows stars instead of the answer, and a parameter is usually the better way in, because a question needs someone at the keyboard and a script that runs on its own has no one there.

Decisions

  1. If This, Then That: `if`, `elseif` and `else` (Apprentice): if runs a block of commands only when its test is True, elseif adds another test, else catches everything left, -and, -or and -not join tests together, and exit stops a script early, so a backup copies only when something changed and explains itself when it can't.
  2. Many Choices: `switch` (Apprentice): switch compares one value with a list of choices and runs the block of each one that matches, with default for anything else; -Wildcard and -Regex match patterns instead of exact text, and a switch on a Read-Host answer makes a simple menu.

Exercise: The Smart Backup

  1. Exercise: The Smart Backup (Apprentice): Finish a backup script that copies a file only when it's needed, with parameters, a usage line, -List and a -Menu, checks for missing, folder and empty names, and a switch that says what kind of file it copied, while a Pester check runs it job by job.