Sunday, March 16, 2025

The Adventurer's Guide to Scripting and Automation with PowerShell (for apprentices)

 

Welcome, brave soul, to the mystical realm of PowerShell! You’ve embarked on a grand quest to master scripting and automation, and I’m your quirky guide, here to lead you through this epic adventure. This post is packed with the essential skills you need, sprinkled with humor, loaded with examples, and brimming with exercises (or as we’ll call them, quests) to keep you engaged. By the end, you’ll be the hero who tames wild servers and automates the chaos of the kingdom.

Table of contents:
Chapter 1: The Basics - Learning the Language of the Land

Chapter 2: Variables - Storing Your Treasures

Chapter 3: Control Structures - Making Decisions and Looping Through Quests

Chapter 4: Functions - Crafting Your Spells

Chapter 5: Error Handling - Surviving Traps and Pitfalls

Chapter 6: Files and Folders - Navigating the Dungeon

Chapter 7: Objects - Understanding the Magic Items

Chapter 8: Modules - Acquiring New Powers

Chapter 9: Remoting - Commanding Allies from Afar

Chapter 10: Automation - The Ultimate Quest


Ready your keyboard, adventurer—let’s dive in!






Chapter 1: The Basics - Learning the Language of the Land

What You’ll Learn: Cmdlets, parameters, and the magical pipeline—the ABCs of PowerShell.

Why It Matters: Every hero needs to speak the local tongue to command the realm!

Example:

Get-Command

This is your treasure map—it lists all the cmdlets at your disposal. Imagine it as a scroll revealing the kingdom’s secrets!

Quest:

Find the cmdlet that lists all files in a directory. (Spoiler: It’s Get-ChildItem). Bonus points: List all .exe files in a folder of your choice with Get-ChildItem -Path "C:\Windows\System32" -Filter "*.exe"".

Now you will need to craft a sword and a health potion in C folder for instance and let your hero know when it is created




# Create a new directory called Hero
New-Item -Path "C:\\Hero" -ItemType Directory

# Create sword.txt file
New-Item -Path "C:\\Hero\\sword.txt" -ItemType File -Value "Damage: 50`nDurability: 100`nType: Legendary"

# Create potion.txt file
New-Item -Path "C:\\Hero\\potion.txt" -ItemType File -Value "Type: Health Potion`nRestore: 50 HP`nDuration: Instant"

Write-Host "Your equipment has been crafted successfully!"

Run this script to create your hero's equipment. The sword and potion files will contain basic stats for your items.


Chapter 2: Variables - Storing Your Treasures

What You’ll Learn: How to declare variables and juggle data types.

Why It Matters? A knight tracks their gold and potions; you’ll track your script’s loot!

Variables: Storing Your Treasures

In PowerShell, variables are your treasure chests—places where you can store your precious loot (data) and use it throughout your journey. By declaring variables and juggling data types, you can organize, manipulate, and track your script's resources just like a knight tracks their gold and potions.

What You’ll Learn: Mastering the Art of Hoarding

  1. Declaring Variables: Create chests to hold your treasures.
  2. Data Types: Know what kind of loot you’re storing (gold coins, potions, or spells).
  3. Manipulating Variables: Manage your treasures to suit your quest’s needs.

Declaring Variables: The Treasure Chest

A variable in PowerShell begins with a $ symbol, followed by a name. It’s your chest where you store values.

Example:

Let’s store some gold coins and potions:

$goldCoins = 100  # Your gold stash
$healingPotions = 5  # Your supply of potions
Write-Output "You have $goldCoins gold coins and $healingPotions healing potions."

Now you’ve got a proper inventory started!

Data Types: Identify Your Loot

Variables can store different types of data (numbers, text, lists). PowerShell is smart and assigns a data type automatically, but understanding data types helps you wield variables more effectively.

Example:

Track various treasures:

$goldCoins = 100  # Integer (number)
$heroName = "Aragorn"  # String (text)
$isCursed = $false  # Boolean (true/false)
$lootBag = @("Sword", "Shield", "Ring of Power")  # Array (list)

Each type of loot helps you in different parts of your quest.

Manipulating Variables: Managing Your Treasures

Change the contents of variables as your adventure progresses—like spending gold or using a potion.

Increment or decrement values

$variable += value # Add to the variable $variable -= value # Subtract from the variable

Example:

Spend gold and drink a potion:

$goldCoins -= 20  # Spend 20 gold
$healingPotions -= 1  # Use one potion
Write-Output "You now have $goldCoins gold coins and $healingPotions healing potions left."

Even knights must budget their resources wisely!

Why It Matters: Track Your Loot

Variables are the foundation of your scripts. They allow you to store, manage, and use data dynamically, making your scripts flexible and reusable. Without them, your adventures would be chaotic and unorganized.

Quest:Create variables for your hero’s name (string), health (integer), and gold (decimal). Then, show off with:

Write-Host "$heroName has $health health and $gold gold pieces."

Sample output: "Aragorn has 100 health and 50.5 gold pieces."


Chapter 3: Control Structures - Making Decisions and Looping Through Quests

What You’ll Learn: If-else decisions, loops (for, foreach, while), and switch statements

.Why It Matters: Dodge traps and slay dragons by using Logic!

Control Structures: The Adventurer’s Compass

Control structures are like the decision-making and movement mechanics in a game. They help you determine your path (if-else decisions), repeat tasks (loops), and choose from multiple options (switch statements). Let’s break it down:

If-Else Decisions: The Hero’s Choice

This structure is your decision-making compass. It evaluates conditions and leads you down the correct path based on the outcome.

Example:

Imagine a dragon guards a chest, and you must decide whether to attack or sneak:

$dragonAwake = $true
if ($dragonAwake) {
    Write-Output "The dragon is awake! Prepare for battle!"
} else {
    Write-Output "The dragon is sleeping. Sneak past it to the treasure."
}

This is your way of making split-second choices to survive and succeed.

Loops: Quest Repetition

Loops allow you to repeat a task until a condition is met or a treasure is found.

  1. For Loop: The Stamina Grind Ideal for adventurers needing to iterate a fixed number of times.

    for ($i = 1; $i -le 5; $i++) {
        Write-Output "Swing sword for the $i time!"
    }
    
  2. Foreach Loop: Gatherer’s Journey Useful when collecting items (like gold coins from a hoard):

    $coins = @("Gold", "Silver", "Bronze")
    foreach ($coin in $coins) {
        Write-Output "You collect a $coin coin."
    }
    
  3. While Loop: Endless Vigil Perfect for quests where the goal is unclear until conditions change:

    $dragonAwake = $true
    while ($dragonAwake) {
        Write-Output "The dragon watches you. Stay hidden..."
        # Simulate the dragon falling asleep
        $dragonAwake = $false
    }
    Write-Output "The dragon is asleep. Make your move!"
    

Switch Statements: The Multi-Path Fork

A switch statement is like choosing which weapon to equip from your arsenal based on the enemy.

Example:

Choose a weapon against your foe:

$enemy = "Goblin"
switch ($enemy) {
    "Goblin" { Write-Output "Equip sword!" }
    "Dragon" { Write-Output "Equip bow!" }
    "Ghost" { Write-Output "Equip magic staff!" }
    Default { Write-Output "Flee! No weapon can save you." }
}

This structure simplifies complex decision-making with multiple options.

Why It Matters: Slay Dragons with Logic

Control structures are your key to crafting scripts that are as dynamic as your epic quests. Whether you're navigating traps, battling monsters, or gathering loot, they let you automate and optimize your actions with precision and finesse.

Example:

$health = 15
if ($health -lt 20) { Write-Host "Drink a potion, quick!" }

Low health? Time to chug that potion!

Quest: Write a loop to simulate battling enemies. Start with 100 health, lose 10 per fight, and stop when health drops below 20. Yell "Retreat!" when you’re done.

Comparison Operators:

Operators Description
-eq Checks if the two operand values are an exact match
-ne Checks if the two operand values are NOT an exact match
-gt Checks if the value of the left operand is greater than the value of the right operand
-lt Checks if the value of the left operand is less than the value of the right operand
-ge Checks if the value of the left operand is greater OR equal to the value of the right operand
-le Checks if the value of the left operand is less OR equal to the value of the right operand


$health = 100
while ($health -ge 20) {
    $health -= 10
    Write-Host "Fought an enemy! Health now: $health"
}
Write-Host "Retreat!"

Chapter 4: Functions - Crafting Your Spells

What You’ll Learn: Build reusable functions with parameters and return values.

Why It Matters: Why swing a sword manually when you can cast a spell once and reuse it?

Example:

function Get-Damage {
    param($strength)
    return $strength * 2
}
Get-Damage -strength 10  # Outputs 20

Double your strength with one incantation!

Quest:Craft a function Get-TotalGold that takes an array of gold amounts and returns the sum. Test it with (5, 10, 15).

function Get-TotalGold {
    param($goldArray)
    return ($goldArray | Measure-Object -Sum).Sum
}
Get-TotalGold -goldArray 5,10,15  # Should output 30

Chapter 5: Error Handling - Surviving Traps and Pitfalls

What You’ll Learn: Try-catch blocks and error handling.

Why It Matters: Even heroes trip; learn to dodge the script-breaking traps!

Error Handling: Surviving the Dungeon of Doom

In PowerShell, errors are like the traps in a dungeon—unexpected, frustrating, and potentially deadly to your script. Learning to handle them effectively ensures that even if you stumble, you can still emerge victorious.

Try-Catch Blocks: Your Shield Against Chaos

Think of a Try-Catch block as your trusty shield. It allows you to attempt risky actions (like opening a trapped chest) and handle the fallout if something goes wrong (like being blasted by a fireball). Here's how it works:

  • Try: Attempt an action that might fail.
  • Catch: Handle the failure gracefully.

Example:

Imagine opening a chest that might contain treasure—or an explosion.

try {
    Write-Output "Opening treasure chest..."
    $chestContent = Get-Item -Path "C:\\Secret\\Treasure.txt"  # Might fail if the file doesn't exist
    Write-Output "You found: $chestContent"
} catch {
    Write-Output "Trap sprung! The chest was rigged. Error: $($_.Exception.Message)"
}

If the chest (file) doesn’t exist, the catch block springs into action to handle the error.

Error Handling Strategies: Potions and Scrolls

Errors come in various forms, like:

  • Non-Terminating Errors: Annoying but won’t stop your journey (like stepping on a squeaky floor tile).
  • Terminating Errors: Serious, potentially game-ending pitfalls (like falling into a pit).

You can use common parameters like -ErrorAction and -ErrorVariable to control how errors are handled:

Get-Item -Path "C:\\Secret\\Treasure.txt" -ErrorAction SilentlyContinue  # Ignore the error

This is like using a silent scroll to continue your quest unbothered.

Why It Matters: Dodge Script-Breaking Traps

Without error handling, your script could crash in the middle of a critical mission. By mastering try-catch blocks, you can recover gracefully, keep your automation running, and triumph even in the face of the unexpected.

Example:

try { Get-Content "secret.txt" } catch { Write-Host "File not found, adventurer!" }

No file? No problem—just a minor detour!

Quest:Write a script to read quest.txt. If it’s missing, announce "No quest found!"

try {
    Get-Content "quest.txt"
} catch {
    Write-Host "No quest found!"
}

Chapter 6: Files and Folders - Navigating the Dungeon

What You’ll Learn: Read, write, and manage files and directories.

Why It Matters: Loot the dungeon and stash your spoils!

Example:

Get-ChildItem -Path "C:\\Treasure"

Explore the treasure hoard at your fingertips!

Quest:Create a script to back up all .txt files from one folder to a new Backup folder.

$source = "C:\\Docs"
$destination = "C:\\Backup"
New-Item -Path $destination -ItemType Directory -Force
Get-ChildItem -Path $source -Filter "*.txt" | Copy-Item -Destination $destination

Chapter 7: Objects - Understanding the Magic Items

What You’ll Learn: Objects, properties, and methods.

Why It Matters: Wield enchanted gear with powers beyond mere variables!

Objects: The Magical Gear

In PowerShell, an object is like a mystical item in your inventory—a sword, potion, or spellbook. It represents something tangible (or magical) with unique attributes and abilities. For example:

  • A sword could be an object with attributes like sharpness, weight, and material.
  • A potion might have properties such as color, volume, and effect.

In PowerShell, everything is treated as an object—files, processes, users—each with its own set of powers to wield.

Properties: The Attributes of Magic Items

Properties are the characteristics or stats of an object. Think of them as the description on your enchanted item:

  • Sword: Damage (50), Weight (5kg), Sharpness ("Very Sharp").
  • Potion: Effect ("Healing"), Quantity (3 doses), Expiry ("Never").

In PowerShell, you access these attributes using dot notation:

$sword = New-Object -TypeName PSObject -Property @{
    Name = "Dragon Slayer"
    Damage = 75
    Material = "Obsidian"
}
Write-Output $sword.Damage  # Outputs: 75

Methods: The Spells and Abilities

Methods are the actions or spells that an object can perform. Imagine:

  • A sword can cast "Swing" or "Parry."
  • A potion can "Heal" when consumed.

In PowerShell, you invoke these abilities with parentheses, like casting a spell:

$sword = New-Object -TypeName PSObject
$sword | Add-Member -MemberType ScriptMethod -Name "Swing" -Value {
    Write-Output "You swing the $($this.Name) with deadly force!"
}
$sword.Name = "Dragon Slayer"
$sword.Swing()  # Outputs: You swing the Dragon Slayer with deadly force!

Why It Matters: Wield the Magic

Objects, properties, and methods in PowerShell let you interact with and manipulate the systems and data around you. They're tools of power that transform mere scripts into dynamic, intelligent solutions—like crafting an enchanted blade from raw ore.

Example:

$sword = New-Object -TypeName PSObject -Property @{Damage=10; Durability=100}
$sword.Damage  # Outputs 10

Behold, a sword object with mighty attributes!

Quest:Create a potion object with Name and HealthRestore properties. Add a Use-Potion method to shout "Health restored!"

$potion = New-Object -TypeName PSObject -Property @{Name="Elixir"; HealthRestore=50}
$potion | Add-Member -MemberType ScriptMethod -Name "Use-Potion" -Value { Write-Host "Health restored!" }
$potion.Use-Potion

Chapter 8: Modules - Acquiring New Powers

What You’ll Learn: Import and use modules for extra cmdlets.

Why It Matters: Unlock ancient tomes of power to expand your arsenal!

Example:

Import-Module Microsoft.PowerShell.Management

Now you’ve got new tricks up your sleeve!

Quest: Import the Microsoft.PowerShell.Management module and use Get-ComputerInfo to display system details.

Import-Module Microsoft.PowerShell.Management
Get-ComputerInfo

Chapter 9: Remoting - Commanding Allies from Afar

What You’ll Learn: PSSessions and remote command execution.

Why It Matters: Rule distant lands without leaving your throne!

Example:

Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Process }

Command your allies across the kingdom!

Quest: Set up a remote session to your local machine (or a test PC) and list all services.

Enter-PSSession -ComputerName "localhost"
Get-Service
Exit-PSSession

Chapter 10: Automation - The Ultimate Quest

What You’ll Learn: Schedule tasks and automate scripts.

Why It Matters: True heroes let their minions—I mean, scripts—do the work!

Automation: The Hero’s Ultimate Quest

Automation in PowerShell is like summoning loyal minions to carry out tasks while you sit on your throne of efficiency. By scheduling tasks and automating scripts, you free yourself from mundane drudgery, letting scripts do all the work so you can focus on grander conquests.

What You’ll Learn: Summoning Your Minions

  1. Task Scheduling: Set scripts to run at specific times or intervals, like sending your squire to patrol the castle gates at sunrise.
  2. Automating Scripts: Create scripts that perform repetitive tasks, from monitoring storage space to preparing battle reports, so you never have to lift a finger again.

Example: The Checkspace Script

Imagine you’re monitoring your kingdom’s treasury (disk space) to ensure you’re not running low. You can create a script like checkspace.ps1 to check the available storage on your servers and warn you if it’s getting low.

Example Script: Save as checkspace.ps1

# Define a threshold for free space (in GB)
$threshold = 10
$drives = Get-PSDrive -PSProvider FileSystem

foreach ($drive in $drives) {
    if ($drive.Free -lt ($threshold * 1GB)) {
        Write-Output "Warning: Drive $($drive.Name) is low on space! Only $($drive.Free / 1GB) GB left."
    } else {
        Write-Output "Drive $($drive.Name) has plenty of space."
    }
}

Scheduling the Script: Let the Minion Work on Its Own

Once you’ve created the checkspace.ps1 script, you can schedule it to run automatically using Task Scheduler in Windows or schtasks.exe from PowerShell. For example:

# Schedule the script to run every day at 8 AM
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\\Scripts\\checkspace.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 8:00AM
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "CheckDiskSpace" -Description "Checks free disk space daily"

Why It Matters: Reclaim Your Time

True heroes of the PowerShell realm know that automation is the key to ultimate power. By scheduling and automating tasks, you can:

  • Eliminate repetitive manual work.
  • Ensure critical tasks are never forgotten.
  • Respond quickly to threats or opportunities.

Example: Save this as checkspace.ps1:

Get-Disk | Where-Object { $_.FreeSpace -lt 10GB } | Write-Host "Low space alert!"

Then schedule it with Task Scheduler!

Quest:Write a script to check free disk space and schedule it to run every morning at 8 AM.

$spaceCheck = {
    $freeSpace = (Get-Disk | Select-Object -First 1).FreeSpace / 1GB
    if ($freeSpace -lt 10) { Write-Host "Warning: Only $freeSpace GB left!" }
}
Register-ScheduledJob -Name "SpaceCheck" -ScriptBlock $spaceCheck -Trigger (New-JobTrigger -Daily -At "8:00 AM")

Final Project: The Grand Automation

The Challenge: Combine your powers to forge an automated system. Monitor disk space, alert on low resources, and clean up temporary files—all hands-free!

Example Start:

$freeSpace = (Get-Disk | Select-Object -First 1).FreeSpace / 1GB
if ($freeSpace -lt 10) { Send-MailMessage -To "hero@kingdom.com" -Subject "Low Space!" -Body "Only $freeSpace GB left!" -SmtpServer "smtp.kingdom.com" }
Remove-Item "C:\\Temp\\*" -Recurse -Force

Schedule it, and you’re the automation king!


Farewell, Hero!

With each quest completed, you’ve leveled up from a novice to a PowerShell legend. Your scripts will hum like a bard’s lute, and your automations will keep the kingdom running smoother than a greased goblin. Go forth, adventurer—may your code be bug-free and your pipelines flow freely!



Share: