Control Flow: If, Loops & Functions
If / ElseIf / Else
Make decisions in your scripts with if, elseif, and else. The condition goes in ( ) and the code to run goes in { }.
Switch — Multiple Conditions
switch is cleaner than a long chain of elseif blocks when you're comparing one value against many possibilities:
For Loop
A for loop repeats code a specific number of times with a counter variable:
ForEach Loop
The foreach loop (not to be confused with ForEach-Object in pipelines) iterates over a collection. It's often cleaner than a for loop when you have an array:
While and Do-While Loops
Functions
Functions let you package reusable code with a name. Define it once, call it many times. Functions in PowerShell use the function keyword:
Advanced Functions with Validation
Add parameter validation to catch bad input early:
Writing Your First Real Script
Let's put it all together with a practical example — a script that checks disk space and warns if it's low:
.ps1 files. Run them with .\myscript.ps1. If you get an execution policy error, run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser once to allow local scripts.🧪 Try It Yourself
- Write an if/else that checks if a number is even or odd (hint: use
%— modulo) - Write a foreach loop that goes through an array of your favorite colors and prints each one
- Write a function called
Get-Greetingthat takes a-Nameparameter and says "Hello, [Name]!" - Copy the disk-check script above into a
.ps1file and run it with your drives - Modify the disk-check to also log results to a text file using
Add-Content
🎉 Congratulations — You've Completed the Beginner Track!
You now know the fundamentals of PowerShell:
- Opening PowerShell, navigating the file system, and using the console
- Variables and all the main data types (strings, numbers, arrays, hashtables)
- Cmdlets, the Verb-Noun pattern, Get-Help, Get-Command, and Get-Member
- The pipeline with Where-Object, Select-Object, Sort-Object, and ForEach-Object
- Control flow with if/else, switch, loops (for, foreach, while), and functions
Next steps: Check the Command Reference to explore more cmdlets, and watch for upcoming Intermediate lessons covering file operations, error handling, regular expressions, and more.