Write the same disk check in Bash and PowerShell
Task
Write a short script, once in Bash on lin-srv and once in PowerShell on win-srv, that loops over every mounted volume, compares its free space with a threshold held in a variable, and prints a warning line for each volume below it. Then test it both ways -- a threshold that should trigger nothing, and one that should trigger everything -- because a check that has never gone red is not known to work.
Steps
- Write
lab/scripts/diskcheck.sh: a variable holding the threshold percentage, taken from the first argument with a default of 10, a loop over the output ofdf -Pskipping the header, and anifthat printsWARN <mount> <free>%when free space is below the threshold. Add a comment explaining the threshold. - Write
lab/scripts/diskcheck.ps1doing the same withparam(),Get-VolumeorGet-PSDrive -PSProvider FileSystem,foreachandif. - Run each with a threshold of 0 and save the output to
lab/scripts/run-0-sh.txtandlab/scripts/run-0-ps.txt. - Run each with a threshold of 100 and save the output to
lab/scripts/run-100-sh.txtandlab/scripts/run-100-ps.txt. - Record the execution policy you used and why in
lab/scripts/policy.txt.
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.
grep -Ec '^[[:space:]]*#' lab/scripts/diskcheck.sh
grep -Ec 'for [a-z_]+ in|while ' lab/scripts/diskcheck.sh; grep -Eic 'foreach' lab/scripts/diskcheck.ps1
cat lab/scripts/run-0-sh.txt lab/scripts/run-0-ps.txt | grep -c WARN
cat lab/scripts/run-100-sh.txt lab/scripts/run-100-ps.txt | grep -c WARN
grep -Eic 'RemoteSigned|AllSigned|signed' lab/scripts/policy.txt
With a threshold of 0 no volume can be below it, so the count must be 0; with 100 every volume is, so the count must be at least one per volume on each server. A script that printed nothing both times has a broken condition, and you would never have found out from the first run alone.
Notes
The Bash loop is where most beginners' scripts break: reading df output word by word instead of line by line, or comparing numbers with a string operator. PowerShell avoids the first problem by passing objects, not text.
This is an independent study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.