Learn POWERSHELL with Real Code Examples
Updated Nov 19, 2025
Code Sample Descriptions
1
PowerShell Counter and Theme Toggle
$count = 0
$isDark = $false
function Update-UI {
Write-Host "Counter: $count"
Write-Host "Theme: $(if ($isDark) { 'Dark' } else { 'Light' })"
}
function Increment { $global:count += 1; Update-UI }
function Decrement { $global:count -= 1; Update-UI }
function Reset { $global:count = 0; Update-UI }
function Toggle-Theme { $global:isDark = -not $global:isDark; Update-UI }
# Simulate actions
Update-UI
Increment
Increment
Toggle-Theme
Decrement
Reset
Demonstrates a simple counter with theme toggling using PowerShell variables and console output.
2
PowerShell Simple Calculator
function Add($a, $b) { $a + $b }
function Subtract($a, $b) { $a - $b }
function Multiply($a, $b) { $a * $b }
function Divide($a, $b) { $a / $b }
Write-Host "Add 5 + 3: $(Add 5 3)"
Write-Host "Subtract 5 - 3: $(Subtract 5 3)"
Write-Host "Multiply 5 * 3: $(Multiply 5 3)"
Write-Host "Divide 6 / 2: $(Divide 6 2)"
Performs basic arithmetic operations using functions.
3
PowerShell Factorial
function Factorial($n) {
if ($n -le 1) { return 1 }
else { return $n * (Factorial ($n - 1)) }
}
Write-Host "Factorial of 5: $(Factorial 5)"
Recursive factorial function.
4
PowerShell Fibonacci Sequence
function Fibonacci($n) {
if ($n -eq 0) { return 0 }
elseif ($n -eq 1) { return 1 }
else { return (Fibonacci ($n - 1)) + (Fibonacci ($n - 2)) }
}
0..9 | ForEach-Object { Write-Host (Fibonacci $_) }
Generate Fibonacci numbers using recursion.
5
PowerShell Array Comprehension
$numbers = 1..10
$squares = $numbers | Where-Object { $_ % 2 -eq 0 } | ForEach-Object { $_ * $_ }
Write-Host $squares
Square even numbers using array operations.
6
PowerShell Hashtable Filtering
$scores = @{ Alice=10; Bob=5; Charlie=12 }
$highScores = $scores.GetEnumerator() | Where-Object { $_.Value -ge 10 } | ForEach-Object { $_.Name, $_.Value }
Write-Host $highScores
Filtering hashtable based on values.
7
PowerShell Anonymous Functions
$add = { param($x,$y) $x + $y }
Write-Host ($add.Invoke(3,7))
Using scriptblocks for anonymous functions.
8
PowerShell Sum of Array
$numbers = 1,2,3,4,5
$sum = 0
foreach ($n in $numbers) { $sum += $n }
Write-Host $sum
Sum elements of an array.
9
PowerShell Zip Arrays
$arr1 = 1,2,3
$arr2 = 4,5,6
for ($i=0; $i -lt $arr1.Length; $i++) { Write-Host ($arr1[$i] + $arr2[$i]) }
Combine two arrays element-wise.
10
PowerShell String Manipulation
$str = 'HelloWorld'
$sub = $str.Substring(0,5)
$len = $str.Length
Write-Host "Substring: $sub, Length: $len"
Substring extraction and length.