PowerShell Reference

A growing library of PowerShell tools and patterns I've put together as a sysadmin. Public and open-source for anyone who wants to learn, copy, or contribute.

View on GitHub

🔤 PowerShell Syntax & Fundamentals

This guide expands on the basics by introducing core PowerShell concepts like variables, logic, loops, and pipelines. This page is designed to be beginner-friendly and explain what each piece does.


📌 1. Variables

Variables in PowerShell store data (text, numbers, objects, arrays, etc.) and always start with a $.

$name = "Alice"
$age = 32
$isAdmin = $true

📝 Notes


🧮 2. Operators

Arithmetic

$sum = 2 + 2       # 4
$diff = 10 - 3     # 7
$product = 4 * 2   # 8

Comparison

Used in logic like if statements:

$a -eq $b    # equal
$a -ne $b    # not equal
$a -lt $b    # less than
$a -gt $b    # greater than

🔁 3. Loops

For Loop

for ($i = 0; $i -lt 5; $i++) {
    Write-Output "Number: $i"
}

While Loop

$count = 1
while ($count -le 3) {
    Write-Output "Loop $count"
    $count++
}

Foreach Loop

$users = @("Alice", "Bob", "Charlie")
foreach ($user in $users) {
    Write-Output "Hello $user"
}

✅ 4. If / Else

if ($age -ge 18) {
    "Adult"
} elseif ($age -lt 18) {
    "Minor"
} else {
    "Unknown"
}

Notes


🧰 5. Functions

Functions let you reuse logic and take input parameters.

function Say-Hello {
    param($name)
    Write-Output "Hello, $name!"
}

Say-Hello -name "Kyle"

🔗 6. Pipelines

PowerShell passes objects from one command to the next using pipes (|).

Get-Service | Where-Object { $_.Status -eq "Running" }

Explanation:


💡 7. Script Blocks

A script block is a block of code stored as an object.

$math = { param($x) $x * 10 }
& $math 5   # 50

📘 8. Comments

Use # for single-line comments:

# This is a comment
Write-Output "Hello"

🧠 Tips


🚀 Keep Going

Next, try writing your own script file (.ps1), or explore: