Step 8. Conditionals and Loops — Making the Computer Judge and Toil

Step 8. Conditionals and Loops — Making the Computer Judge and Toil

Level 0 — Understanding How to Operate a Computer and How It’s Structured | Difficulty ★★☆☆☆ | Estimated time: 3 hours

Prerequisites: Step 7 complete. We’ll work in Windows PowerShell. No internet connection needed.

  • What you need: a Windows PC, PowerShell.
  • Safety: today is again entirely safe practice code.
  • Caution: the comparison symbols are unusual. PowerShell uses -gt instead of >, and -eq instead of =. It feels awkward, but the rules are simple — get it wrong once and it becomes familiar fast.

Today is truly day one of "a script that feels like a script." In Step 4 you handled a log file, but real server logs pile up tens of thousands of lines per day. What a security professional needs is "tell me if failed logins exceed 5" (conditional judgment) and "examine every single log line" (repetition). Done by a person, it takes days and invites mistakes; a computer does it in a second and never tires. The two tools you’ll learn today are the heart of that automation.


1. Learning Objectives

By the end of this chapter, you can:

  • Turn "if ~ then" judgments into code with if/else
  • Sweep an entire list automatically with foreach, and repeat a fixed number of times with for
  • Combine condition + loop to build "pick out only what matches (filtering)"
  • Complete the even-number-sum script for 1–100 with the accumulation pattern (totals and counts)

2. Background Knowledge — Today’s Tools and Concepts

Today’s Tools at a Glance

Category Details
Language/environment PowerShell 5.1 (a day for learning concepts common to all programming — they exist unchanged in other languages)
Today’s syntax if (condition) { } else { }, foreach ($x in $list) { }, for ($i=1; $i -le N; $i++) { }
Comparison operators -eq -ne -gt -lt -ge -le (plus the remainder %)
Concepts you need control flow, conditional expressions (true/false), loops, the accumulation pattern

If variables are the alphabet, conditionals and loops are grammar. You’re already using both concepts in daily life — "if it rains, take an umbrella" (condition), "wait until the elevator arrives" (repetition). Today is merely the practice of moving these into code.

2-1. Control Flow — Dams and Channels on a Stream

A program flows top to bottom by default. This flow is called control flow. Today’s two tools are devices attached to that flow:

  • Conditional (if) — a sluice gate that splits the flow: "if this condition is true, go to A; otherwise, to B"
  • Loops (foreach, for) — a circulating channel that runs the same stretch over many rounds

No matter how different programming languages are, these two always exist. Python, C, JavaScript — all of them. Learn one properly, and in other languages you just swap the notation.

2-2. Conditional Expressions — Questions Answered True/False

A conditional needs a "judgment criterion." That’s the conditional expression, and its answer is always one of two: True or False.

$a -gt 5 — "is a greater than 5?" If a is 7, true; if 3, false. Here’s PowerShell’s comparison operator table:

Operator Meaning Example Result
-eq equals $a -eq 5 true if a is 5
-ne not equal $a -ne 5 true if a is not 5
-gt greater than $a -gt 5 true if a is 6 or more
-lt less than $a -lt 5 true if a is 4 or less
-ge greater than or equal $a -ge 5 true if a is 5 or more
-le less than or equal $a -le 5 true if a is 5 or less

Caution: math’s = is "assignment" (putting into a box) in PowerShell. Comparing for equality is always -eq. $a = 5 is "put in 5"; $a -eq 5 is "is it equal to 5?" — confusing these is the beginner’s greatest bug factory.

2-3. The Two Faces of Repetition

Two kinds of repetition are used depending on the situation:

  • foreach — "for each item in the list, one at a time" (calling roll down a member roster)
  • for — "a set number of times" (run 10 laps)

Both are "repetition," but they start from different places. If you have a list, foreach; if the count is fixed, for. Today we’ll do both.


3. Follow Along

3-1. First Conditional — if

$a = 7
if ($a -gt 5) { "Big" } else { "Small" }
Big

How to read the output: since $a is 7, "is it greater than 5?" is true → the { "Big" } side ran.

Structural breakdown: if (conditional expression) { what to do when true } else { what to do when false }. The curly braces { } are "bundles of things to do."

Why do this: now change $a to 3 and run it again:

$a = 3
if ($a -gt 5) { "Big" } else { "Small" }

This time Small comes out. Same code, different behavior depending on the value — that’s the power of conditionals. Your code has started reacting to situations on its own.

3-2. if Without else, and a Real-World Condition

When there’s nothing to do on false, omit the else:

$failCount = 7
if ($failCount -ge 5) { "Warning: too many login failures!" }
Warning: too many login failures!

Why do this: this shape is the basic form of a security alert. "If the failure count is at or above the threshold (5), warn." Change $failCount to 2 and there’s no output at all — silence is normal.

Predict first: if you use -gt instead of -ge, as in if ($failCount -gt 5) { ... }, will the warning appear when failures are exactly 5? (Answer: no. -gt means "greater than," so 5 isn’t included. How behavior changes at the boundary value — exactly at the threshold number — is a classic seat of programming mistakes. Put in 5 yourself and check.)

3-3. foreach — Automatically Sweeping a List

Let’s bring back the array from Step 7:

$members = @("Kim", "Lee", "Park")
foreach ($m in $members) { "Hello, $m!" }
Hello, Kim!
Hello, Lee!
Hello, Park!

How to read the output: it ran once per list item, three times total.

Structural breakdown: foreach ($m in $members) — "pull out one at a time from the members list, calling it m" — and run the inside of { }. $m changes each round: first round Kim, second round Lee, third round Park.

Why do this: in real work this pattern transforms like this — "pull files one by one from a file list and inspect," "pull users one by one from a user list and check permissions." Whether it’s 100 items or a million, the code stays the same one line.

3-4. for — Repeating a Fixed Number of Times

for ($i = 1; $i -le 5; $i++) { "Number $i" }
Number 1
Number 2
Number 3
Number 4
Number 5

Structural breakdown — the parentheses hold three pieces:

  • $i = 1 — starting value (start with i at 1)
  • $i -le 5 — condition to keep going (repeat only while i is 5 or less)
  • $i++ — what to do at the end of each round (add 1 to i — ++ is the symbol for "increment by 1")

Why do this: use it when you need numeric repetition of the form "from n to m" without a list. Checking ports 1 through 1024 is a real-world example.

3-5. Condition + Loop Combined — Filtering

Now let’s combine the two. "From a list, pick out only what matches the condition":

$scores = @(85, 42, 91, 55, 78)
foreach ($s in $scores) {
    if ($s -ge 60) { "$s points: Pass" }
}
85 points: Pass
91 points: Pass
78 points: Pass

How to read the output: 42 and 55 didn’t meet the condition (60 or more), so they were filtered out. The loop ran over everything, and the conditional selected what to print.

Why do this: "sweep everything, process only what matches" — that’s exactly how log analysis works. Tens of thousands of lines driven through a foreach, hooked by a condition like "contains ERROR." Today’s 5 lines are that principle in miniature.

3-6. The Grand Synthesis — Summing the Even Numbers

Let’s do today’s completion-criteria assignment together: sum only the even numbers from 1 to 100.

First, how to tell an even number: a number whose remainder when divided by 2 is 0 is even. The remainder operator is %. If $n % 2 is 0, it’s even.

$sum = 0
for ($i = 1; $i -le 100; $i++) {
    if ($i % 2 -eq 0) { $sum = $sum + $i }
}
$sum
2550

Line-by-line explanation:

  1. $sum = 0 — prepare the box that will hold the total at 0 (an empty pocket)
  2. Repeat from 1 to 100, and
  3. $i % 2 -eq 0 — if it divides evenly (if it’s even)
  4. $sum = $sum + $i — add that number into the pocket. The right side is calculated first, and the result goes back into $sum
  5. Final output: 2550 (2+4+6+…+100, verified by actual run)

Why do this: "accumulation" (stacking up a value while repeating) is a basic pattern of data processing. Total error count, total bytes transferred, average calculation — they all take this shape.

3-7. Real-World Connection — Merging with Step 4’s Log

Let’s connect, as a taste, how today’s techniques are used on an actual log file. First, make a test log (same trick as Step 4’s generator):

1..20 | ForEach-Object { if ($_ % 3 -eq 0) { Add-Content scanlog.txt "ERROR number $_" } else { Add-Content scanlog.txt "OK number $_" } }

Now read the file into an array (Step 7), and filter by condition while looping:

$lines = Get-Content scanlog.txt
$errCount = 0
foreach ($line in $lines) {
    if ($line.Contains("ERROR")) { $errCount = $errCount + 1 }
}
"Out of $($lines.Count) lines total, $errCount errors"
Out of 20 lines total, 6 errors

Line-by-line explanation:

  1. Get-Content — reads the whole file into a line-by-line array. 20 lines means a 20-slot array
  2. $errCount = 0 — prepare the accumulation pocket (section 3-6’s pattern)
  3. foreach — walk the 20 lines one by one
  4. $line.Contains("ERROR") — a conditional expression asking "does this line contain the text ERROR?" True if it does
  5. Final report — remember the $($lines.Count) notation inside double quotes?

Why do this: these seven lines are the minimal complete form of a "log analysis script." Read a file, sweep it all, count by condition, state a summary — real-world log analysis never escapes this structure; it only grows in scale. Right now you’re watching the moment when three skills — Step 4 (text search), Step 7 (variables & arrays), Step 8 (conditionals & loops) — merge into a single tool.


4. Missions & Exercises

Mission — Login Watch Script (Miniature)

Let’s build a model of real security log monitoring. Below are one user’s login failure counts by time slot:

$failLog = @(0, 1, 0, 3, 9, 12, 2, 0)

Tasks:

  1. Walk this list with foreach, and for time slots with 5 or more failures, print "Danger: N failures"
  2. After the loop ends, print the total of all failures as "Total failures: M" (use the accumulation pattern)

Exercises

Exercise 1. Explain the difference between $a = 5 and $a -eq 5.

Exercise 2. What’s the criterion for choosing between foreach and for?

Exercise 3. Write code that prints only values 5 or greater from @(3, 7, 2, 8).

Exercise 4. I ran an accumulation-pattern script twice in a row and the total doubled. Cause and fix?


5. Model Answers & Completion Criteria

Mission Model Answer

$failLog = @(0, 1, 0, 3, 9, 12, 2, 0)
$sum = 0
foreach ($f in $failLog) {
    if ($f -ge 5) { "Danger: $f failures" }
    $sum = $sum + $f
}
"Total failures: $sum"

Expected output (verified by actual run):

Danger: 9 failures
Danger: 12 failures
Total failures: 27

How to verify: perfect if "Danger" appears on exactly two lines and the total is 27. If Danger appears on three or more lines, recheck the condition. If the total differs, you very likely left out the $sum initialization (= 0).

Deeper dive: if you change the condition to -gt 5, which lines disappear? Predict with your reasoning, then check. (Answer: none. Both 9 and 12 are greater than 5, so the result is the same. Instead, compare -ge 9 vs -gt 9 with the threshold raised to 9 — then the boundary-value difference becomes unmistakable.)

Exercise Answers

Answer 1. $a = 5 is assignment — the act of putting 5 into a box. $a -eq 5 is comparison — the question "is a equal to 5?", answered true/false. Writing = in a condition slot is the beginner’s greatest bug.

Answer 2. If the list you need to handle already exists, foreach ("for each item in the list, one at a time"); if a count or numeric range is fixed, for ("from 1 to 100").

Answer 3.

$nums = @(3, 7, 2, 8)
foreach ($n in $nums) {
    if ($n -ge 5) { $n }
}

The output is 7 and 8. "Sweep everything, process only what matches" — the filtering pattern.

Answer 4. Either you left out the $sum = 0 initialization, or you re-ran in the same PowerShell window with the previous run’s $sum still alive (variables live while the window is open — Step 7 review). Put $sum = 0 at the top of the script and run the whole thing from the start every time.

Completion Checklist

  • [ ] I can distinguish and use comparison operators like -eq, -gt, -lt
  • [ ] I can explain the difference between = and -eq
  • [ ] I can write branching by condition with if/else
  • [ ] I can walk every item of an array with foreach
  • [ ] I can write count-based repetition with for
  • [ ] I can compute totals with the accumulation pattern
  • [ ] Mission: I completed the login watch script (miniature)

6. Common Pitfalls & Fixes

Wall 1. I keep confusing = and -eq

Symptom: wrote if ($a = 5) and the condition behaves as if always true, or results are weird.
Cause: = is not comparison but assignment. It "puts 5 into a" and then judges by that value (5).
Fix: in a condition slot, it’s -eq, unconditionally. "Is it equal?" is -eq; "put it in" is = — brand it into your head.

Wall 2. The loop never runs, or never ends

Symptom: typed a for loop and got no output, or it won’t stop.
Cause: the condition is often written backwards. for ($i=1; $i -ge 100; $i++) is false the moment it starts, so it never runs. The reverse — a condition that’s true forever — loops infinitely.
Fix: if it won’t stop, interrupt with Ctrl + C. Then check just two things: "does the starting value satisfy the condition?" and "does the condition move toward false each round?"

Wall 3. The curly braces { } don’t pair up

Symptom: typed code across multiple lines and a >> prompt keeps asking for more input.
Cause: you opened { and never closed it with }, so PowerShell is waiting, thinking "not done yet."
Fix: type an extra }, or cancel with Ctrl + C and retype. Habit: the instant you type {, type } too, then fill in between them.

Wall 4. The total is weirdly large, or 0

Symptom: the accumulation result isn’t what I expected.
Cause: two classic ones. ① You left out $sum = 0 initialization (adding into a nonexistent pocket). ② You ran the code multiple times in the same window without resetting the variable — the previous run’s $sum remains and keeps stacking.
Fix: put $sum = 0 at the top of the script, and every time you run, run the whole thing from the start.

Wall 5. I get confused at the boundary of -gt and -ge

Symptom: I wanted "5 or more," but it doesn’t trigger at 5.
Cause: you used -gt (greater than), so 5 was excluded. "Or more" is -ge; "greater than" is -gt.
Fix: test by putting in the threshold number itself (boundary-value testing). Decide "what should happen at exactly 5?" first, then pick the code — mistakes shrink.


7. Summary

Today’s Two Pillars

Tool Purpose Form
if / else fork by condition if (condition) { A } else { B }
foreach sweep an entire list foreach ($x in $list) { ... }
for repeat a fixed count for ($i=1; $i -le N; $i++) { ... }

Comparison Operator Cheat Sheet

-eq (equals) -ne (not equal) -gt (greater than) -lt (less than) -ge (or more) -le (or less) — and = is assignment, % is remainder.

Today’s Pattern Card

Pattern Code skeleton Real-world use
Threshold alert if ($n -ge threshold) { warn } failed-login alerts
Filtering if inside foreach extracting only anomalies from logs
Accumulation $sum = 0, then add while looping totals and grand totals

Instincts That Matter More Than Commands

Intrusion detection rules, log analysis, alerting systems — all of them stand on today’s "condition + loop." Being able to write "warn at 5 or more failures" as code means you’re no longer a person who reads logs with your eyes but a person who builds programs that inspect logs.

Remember too that the same tools serve both offense and defense. An attacker uses for to try password candidates one by one (brute force — you’ll practice this yourself in a lab environment in Level 2); a defender uses foreach to sweep connection logs for anomalies. Firewall rules and access controls are, in the end, giant collections of if statements.


Once every box is checked, Step 8 is complete.