Read a script before running it, then run it with -WhatIf

short · 35 min · Objective 1.2

Task

Write a short reporting script, then practise the skill that matters more: reading a script written by someone else and deciding whether it should run. The reading checklist is the deliverable, because a support technician is asked to make that judgement far more often than to write anything.

Steps

  1. Write a script at lab/ps/report.ps1 that outputs the ten processes using the most memory, with their names and memory figures, and run it. Save its output to lab/ps/report.txt.
  2. Record the current execution policy in lab/ps/policy.txt along with one sentence on why RemoteSigned is the usual working answer and why policy is not a security boundary.
  3. Write lab/ps/checklist.md giving at least six things to look for when reading an unfamiliar script, each with why it matters.
  4. Write a second script at lab/ps/risky.ps1 that would delete the files in lab/ps/victims/ (create it with two or three empty files), add -WhatIf support with [CmdletBinding(SupportsShouldProcess)], and run it with -WhatIf -- nothing is deleted. Capture the output with Start-Transcript -Path lab/ps/whatif.txt, run the script, then Stop-Transcript. Do not redirect with >: the "What if:" lines go to the console, not the output stream, and in Windows PowerShell 5.1 .\risky.ps1 -WhatIf > whatif.txt leaves an EMPTY file even though the switch worked.
  5. Write lab/ps/extensions.csv with header extension,interpreter,typical_risk covering at least five script file types.

Verify

These checks run in a POSIX shell: Terminal on macOS or Linux, and on Windows Git Bash (it comes with Git for Windows) or WSL. A stock Windows PowerShell or Command Prompt has no awk or grep, so there the first line fails.

test -s lab/ps/report.ps1 && grep -Eic 'get-process' lab/ps/report.ps1
grep -c . lab/ps/report.txt
grep -Eic 'restricted|remotesigned|allsigned|bypass' lab/ps/policy.txt
grep -Ec '^[-*0-9]' lab/ps/checklist.md
grep -Eic 'what ?if:' lab/ps/whatif.txt       # the lines PowerShell printed
ls lab/ps/victims | wc -l                     # must not be 0: nothing was deleted
awk -F, 'NR>1 && NF>=3 {n++} END {print n" extension(s)"}' lab/ps/extensions.csv

Six or more checklist items, a policy note naming an actual policy value, and -WhatIf output showing what would have happened, and the victims still there. An empty whatif.txt does not by itself mean the switch was missed -- redirecting with > produces one even when it worked, which is why the transcript is used; the file count is what says whether anything was deleted.

Notes

Appending -WhatIf first is worth building into a habit now. It is the single most valuable feature of the language for a support role, and it costs six characters.

This is an independent study companion for CompTIA A+ Core 2 220-1202 and is not produced by or endorsed by CompTIA.