TExcelTAD
Home › PowerShell › PowerShell Exercises

PowerShell Exercises

Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. On this site PowerShell examples are simulated, so copy the starter into your own pwsh session (or a .ps1 file), replace the TODO parts and compare your output with the "Expected" lines. Try for a few minutes before opening the solution.

# Exercise Topics
1 Temperature table for loop, -f formatting
2 Vowel counter functions, regex
3 FizzBuzz if/elseif, %, collecting loop output
4 Top words -split, Group-Object, Sort-Object
5 Files by extension files, Group-Object
6 Salary report CSV, Group-Object, Measure-Object
7 Safe percentage advanced functions, validation, try/catch
8 Merge settings ordered hashtables, JSON

1. Temperature table

Print a Celsius-to-Fahrenheit table for 0, 10, 20, 30 and 40 °C using F = C × 9 / 5 + 32. Right-align Celsius in 3 characters and Fahrenheit in 5 with one decimal.

Expected first line 0 C = 32.0 F, last line 40 C = 104.0 F.

powershell · try it yourself
# TODO: loop from 0 to 40 in steps of 10 and use '{0,3} C = {1,5:N1} F' -f ...
foreach ($c in 0) {
    $f = 0  # TODO: the formula
    "$c C = $f F"
}
0 C = 0 F
Show solution
powershell
for ($c = 0; $c -le 40; $c += 10) {
    $f = $c * 9 / 5 + 32
    '{0,3} C = {1,5:N1} F' -f $c, $f
}

2. Vowel counter

Write Get-VowelCount -Text <string> that returns how many vowels (a e i o u, any case) the text contains.

Expected: Get-VowelCount 'PowerShell is fun' → 5, Get-VowelCount 'AEIOU xyz' → 5.

powershell · try it yourself
function Get-VowelCount {
    param([string]$Text)
    0   # TODO: count the vowels
}
Get-VowelCount 'PowerShell is fun'
Get-VowelCount 'AEIOU xyz'
0
0
Show solution
powershell
function Get-VowelCount {
    param([string]$Text)
    ([regex]::Matches($Text, '[aeiou]', 'IgnoreCase')).Count
}

Alternative without regex: @($Text.ToLower().ToCharArray() | Where-Object { $_ -in 'a','e','i','o','u' }).Count.

3. FizzBuzz

For the numbers 1 to 15, output Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Print the results on one line separated by spaces.

Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

powershell · try it yourself
$out = foreach ($n in 1..15) {
    $n   # TODO: replace with the FizzBuzz rules
}
$out -join ' '
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
powershell
$out = foreach ($n in 1..15) {
    if ($n % 15 -eq 0)    { 'FizzBuzz' }
    elseif ($n % 3 -eq 0) { 'Fizz' }
    elseif ($n % 5 -eq 0) { 'Buzz' }
    else                  { $n }
}
$out -join ' '

Check 15 first: otherwise the % 3 branch would win for 15.

4. Top words

Find the three most frequent words in the text and print them as word: count, most frequent first (ties broken by name, descending).

Expected:

text
the: 3
and: 2
quick: 1
powershell · try it yourself
$text = 'the quick fox and the lazy dog and the cat'
# TODO: split into words, group, sort by count, take 3
$words = $text -split '\s+'
"$($words.Count) words in total"
10 words in total
Show solution
powershell
$text -split '\s+' |
    Group-Object |
    Sort-Object Count, Name -Descending |
    Select-Object -First 3 |
    ForEach-Object { "$($_.Name): $($_.Count)" }

5. Files by extension

The starter creates six files. Report how many files there are per extension, most common first.

Expected:

text
.txt 3
.log 2
.csv 1
powershell · try it yourself
New-Item -ItemType Directory ./ex5 -Force | Out-Null
'a.txt', 'b.txt', 'c.log', 'd.csv', 'e.txt', 'f.log' | ForEach-Object { Set-Content "./ex5/$_" 'x' }

# TODO: group the files by their Extension property
Get-ChildItem ./ex5 -File | Measure-Object | ForEach-Object { "$($_.Count) files" }
6 files
Show solution
powershell
Get-ChildItem ./ex5 -File |
    Group-Object Extension |
    Sort-Object Count -Descending |
    ForEach-Object { '{0} {1}' -f $_.Name, $_.Count }

6. Salary report

From the CSV text, print each department (alphabetically) with its head count and average salary, formatted with thousands separators.

Expected:

text
Engineering  2 people, avg 8,350
Research     2 people, avg 8,050
Sales        1 people, avg 6,100
powershell · try it yourself
$csv = @'
Name,Department,Salary
Ada,Research,8200
Linus,Engineering,7600
Grace,Engineering,9100
Alan,Research,7900
Joan,Sales,6100
'@
$staff = $csv | ConvertFrom-Csv
# TODO: Group-Object Department, then Measure-Object Salary -Average per group
"$($staff.Count) employees loaded"
5 employees loaded
Show solution
powershell
$staff | Group-Object Department | Sort-Object Name | ForEach-Object {
    $avg = ($_.Group | Measure-Object Salary -Average).Average
    '{0,-12} {1} people, avg {2:N0}' -f $_.Name, $_.Count, $avg
}

Measure-Object converts the CSV strings to numbers for you.

7. Safe percentage

Write an advanced function Get-Percentage -Part <n> -Total <n> that returns the percentage with one decimal and a % sign. Both parameters are mandatory, and -Total must be at least 1 (use a validation attribute, not an if). Call it once correctly and once with -Total 0 inside try/catch.

Expected:

text
74.0%
Total must be at least 1
powershell · try it yourself
function Get-Percentage {
    param($Part, $Total)   # TODO: CmdletBinding, Mandatory, ValidateRange
    "$Part of $Total"
}
Get-Percentage -Part 37 -Total 50
37 of 50
Show solution
powershell
function Get-Percentage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][double]$Part,
        [Parameter(Mandatory)][ValidateRange(1, [double]::MaxValue)][double]$Total
    )
    '{0:N1}%' -f ($Part / $Total * 100)
}
Get-Percentage -Part 37 -Total 50
try { Get-Percentage -Part 5 -Total 0 } catch { 'Total must be at least 1' }

8. Merge settings

Combine the default settings with the overrides (overrides win), keeping the key order of the defaults, and print the result as compressed JSON.

Expected: {"port":9090,"debug":true,"name":"app"}

powershell · try it yourself
$defaults = [ordered]@{ port = 8080; debug = $false; name = 'app' }
$overrides = @{ debug = $true; port = 9090 }
# TODO: build $merged from both tables
$merged = $defaults
$merged | ConvertTo-Json -Compress
{"port":8080,"debug":false,"name":"app"}
Show solution
powershell
$merged = [ordered]@{}
foreach ($k in $defaults.Keys)  { $merged[$k] = $defaults[$k] }
foreach ($k in $overrides.Keys) { $merged[$k] = $overrides[$k] }
$merged | ConvertTo-Json -Compress

Copying into a new table keeps $defaults unchanged, so you can reuse it for another environment.

Test yourself

In FizzBuzz, why must the % 15 test come before % 3?

  1. It is faster
  2. Because if/elseif stops at the first true branch, and 15 is also divisible by 3
  3. PowerShell evaluates elseif in reverse
  4. It doesn't matter

Which pipeline counts files per extension?

  1. Get-ChildItem | Measure-Object Extension
  2. Get-ChildItem -File | Group-Object Extension
  3. Get-ChildItem | Sort-Object Extension -Unique
  4. Get-ChildItem | Select-Object Extension -Count