Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 34 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded PowerShell exercises on the pipeline, functions, errors and files, each with a read-only PowerShell solution and a runnable JavaScript equivalent.

PowerShell is learned with your fingers. Reading about Group-Object is not the same as using it to answer a question you actually had. This page gives you twelve small tasks that run from beginner to advanced and cover the four skills the course built up: the pipeline, functions, errors and files.

Real PowerShell cannot run on this site, so each solution is shown as read-only PowerShell that you can paste into your own console (PowerShell 7 or Windows PowerShell 5.1). Next to it, every group has a runnable JavaScript equivalent in the editor. It is not PowerShell, but it follows the same steps on the same sample data, so you can check the logic, change the data and see the result. Where the two differ, the text says so.

How to practice well:

  • Try first, peek later. Write your own answer in a console before you open a solution.
  • Run it for real. The PowerShell solutions are short and safe. Exercise 12 touches only a temporary folder and cleans up after itself.
  • Explain the difference. After each solution, ask yourself what would happen with different data. That question is the real exercise.

The sample file list is created with ConvertFrom-Csv, exactly like Import-Csv would read a file. That means every value is a string, including the sizes. This is deliberate: it is the most common reason a sort looks wrong. See CSV, JSON and XML.

The shared sample data

Exercises 1 to 3 use this list of files. Paste it into your console first.

POWERSHELL
$files = @'
Name,Ext,SizeKB
report.docx,.docx,240
photo1.jpg,.jpg,3100
photo2.jpg,.jpg,2800
notes.txt,.txt,4
budget.xlsx,.xlsx,520
backup.zip,.zip,50400
readme.txt,.txt,2
'@ | ConvertFrom-Csv

Group A: The pipeline

These practice Where-Object, Select-Object and Sort-Object and Group-Object, Measure-Object and ForEach-Object.

1. Big files first (Beginner)

Show the name and size of every file larger than 500 KB, biggest first. Make sure the sizes are compared as numbers, not as text.

Solution 1
POWERSHELL
$files |
    Select-Object Name, @{ Name = 'SizeKB'; Expression = { [int]$_.SizeKB } } |
    Where-Object SizeKB -gt 500 |
    Sort-Object SizeKB -Descending

The result has four rows: backup.zip (50400), photo1.jpg (3100), photo2.jpg (2800) and budget.xlsx (520). The calculated property replaces the string with an [int] before filtering and sorting. Without the cast, Sort-Object SizeKB would sort text and put "520" after "50400".

2. Totals per extension (Beginner)

For each file extension, show how many files there are and their total size, largest total first.

Solution 2
POWERSHELL
$files |
    Group-Object Ext |
    ForEach-Object {
        [pscustomobject]@{
            Ext     = $_.Name
            Files   = $_.Count
            TotalKB = ($_.Group | ForEach-Object { [int]$_.SizeKB } | Measure-Object -Sum).Sum
        }
    } |
    Sort-Object TotalKB -Descending

Expected order: .zip (1 file, 50400), .jpg (2 files, 5900), .xlsx (1, 520), .docx (1, 240), .txt (2, 6). The inner ForEach-Object casts each size to [int] before Measure-Object adds them up. The -Sum result is a real number, so the final sort is numeric.

3. Sizes in megabytes (Intermediate)

Add a SizeMB property (rounded to two decimals, 1 MB = 1024 KB) and show the three largest files.

Solution 3
POWERSHELL
$files |
    Select-Object Name, @{ Name = 'SizeKB'; Expression = { [int]$_.SizeKB } } |
    Sort-Object SizeKB -Descending |
    Select-Object -First 3 Name, SizeKB,
        @{ Name = 'SizeMB'; Expression = { [math]::Round($_.SizeKB / 1024, 2) } }

Expected values: backup.zip 49.22, photo1.jpg 3.03 and photo2.jpg 2.73. Sorting before -First 3 matters: Select-Object -First takes the first items it sees and has no idea which are the largest.

Here is the JavaScript equivalent of the three solutions. Number() plays the role of [int], and filter, sort and slice play Where-Object, Sort-Object and Select-Object -First.

JS Stand-in for exercises 1 to 3: the pipeline

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first two lines of output show the trap: the text sort puts 2, 240, 2800, 3100, 4, 50400, 520, the numeric sort puts them in the order you expect. Change "520" to "5" and rerun to see the text sort get even stranger.

Group B: Functions

These practice Functions and Parameters and Advanced Functions.

4. A converter that accepts the pipeline (Beginner)

Write ConvertTo-Fahrenheit with a mandatory [double]$Celsius parameter that also accepts values from the pipeline, so 0, 37, 100 | ConvertTo-Fahrenheit works.

Solution 4
POWERSHELL
function ConvertTo-Fahrenheit {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [double]$Celsius
    )
    process {
        $Celsius * 9 / 5 + 32
    }
}

0, 37, 100 | ConvertTo-Fahrenheit

The output is 32, 98.6 and 212. The process block runs once for each incoming value. Without it, only the last value would be handled, because the function body would run once in the end position.

5. Stop the leak (Intermediate)

This function should return only the list of unique words, but it also prints True and False lines. Find the cause and fix it without changing the result.

POWERSHELL
function Get-UniqueWord {
    param([string[]]$Word)
    $seen = [System.Collections.Generic.HashSet[string]]::new()
    foreach ($w in $Word) {
        $seen.Add($w)
    }
    $seen
}
Solution 5

HashSet.Add() returns a Boolean, and in PowerShell every value a statement produces goes to the output stream unless you capture it. Each Add call leaks True (new word) or False (duplicate). Discard the result:

POWERSHELL
function Get-UniqueWord {
    param([string[]]$Word)
    $seen = [System.Collections.Generic.HashSet[string]]::new()
    foreach ($w in $Word) {
        [void]$seen.Add($w)      # or: $null = $seen.Add($w)
    }
    $seen
}

Get-UniqueWord 'red', 'green', 'red', 'blue'

The output is red, green and blue. [System.Collections.ArrayList]::Add() leaks its index in the same way, while System.Collections.Generic.List[T].Add() returns nothing and does not.

6. Limit the choices (Intermediate)

Write Get-Greeting -Name <string> -Style <Formal|Casual>. -Style must accept only those two values and default to Casual. Formal returns Good day, <Name>.; casual returns Hi <Name>!.

Solution 6
POWERSHELL
function Get-Greeting {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Name,

        [ValidateSet('Formal', 'Casual')]
        [string]$Style = 'Casual'
    )
    if ($Style -eq 'Formal') { "Good day, $Name." }
    else                     { "Hi $Name!" }
}

Get-Greeting -Name Ada -Style Formal    # Good day, Ada.
Get-Greeting -Name Ada                  # Hi Ada!
Get-Greeting -Name Ada -Style Rude      # error: value is not in the allowed set

ValidateSet also gives you tab completion of the allowed values for free. The check runs when the parameter is bound, before any line of your function body runs.

The JavaScript equivalent has no pipeline binding, so the "process block" is a function applied to each item, and the validation is an explicit check.

JS Stand-in for exercises 4 to 6: functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the leaky version, the Booleans (true, true, false, true) appear before the words, which is exactly what you see in PowerShell: the function's output is everything it emitted, in order.

Group C: Errors

These practice Errors, try/catch and ErrorAction.

7. Catch a missing file (Beginner)

Try to read C:\does-not-exist.txt with Get-Content. Make a missing file a catchable error and print only the message, prefixed with Failed: .

Solution 7
POWERSHELL
try {
    Get-Content -Path 'C:\does-not-exist.txt' -ErrorAction Stop
}
catch {
    "Failed: $($_.Exception.Message)"
}

Get-Content reports a missing file as a non-terminating error: it writes the error and carries on, so catch never runs. -ErrorAction Stop upgrades it to terminating, and then catch runs. Inside catch, $_ is the error record and $_.Exception.Message is the readable text (here, that the path cannot be found because it does not exist).

8. Predict the order (Intermediate)

What does this print? Work it out on paper first, then run it.

POWERSHELL
function Test-Flow {
    try     { 'A'; throw 'boom'; 'B' }
    catch   { 'C: ' + $_.Exception.Message }
    finally { 'D' }
    'E'
}
Test-Flow
Solution 8

The output is four lines: A, C: boom, D, E.

'A' is emitted, then throw jumps out of the try block, so 'B' is never reached. The catch block runs and emits its message. The finally block always runs, error or not, and then execution continues after the whole statement with 'E'. Remove the throw and you get A, B, D, E: catch is skipped but finally still runs.

9. Count the failures (Advanced)

Given the list '12', 'ab', '7x', '40', convert each to [int]. Print how many conversions worked, how many failed and the sum of the good ones. A failure must not stop the loop.

Solution 9
POWERSHELL
$ok = 0; $failed = 0; $sum = 0
foreach ($text in '12', 'ab', '7x', '40') {
    try {
        $sum += [int]$text
        $ok++
    }
    catch {
        $failed++
    }
}
"ok=$ok failed=$failed sum=$sum"

The output is ok=2 failed=2 sum=52. The cast [int]'ab' throws a conversion error, which catch handles, and the foreach loop continues with the next item. Note the order inside try: the $ok++ line is placed after the risky conversion, so it only runs when the conversion succeeded. For a hot loop, [int]::TryParse() avoids exceptions altogether.

The JavaScript equivalent uses Number() with a strict check, since Number("7x") gives NaN instead of throwing, a good reminder that every language defines "failure" a little differently.

JS Stand-in for exercises 7 to 9: errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Group D: Files and data

These practice Working with Files and Folders, CSV, JSON and XML and Regular Expressions and Text Processing.

10. Count the errors in a log (Intermediate)

Write the lines below to a temporary file app.log and count the lines that contain ERROR.

TEXT
2025-03-01 10:00:01 INFO  start
2025-03-01 10:00:05 ERROR disk full
2025-03-01 10:01:00 WARN  slow query
2025-03-01 10:02:30 ERROR timeout
2025-03-01 10:03:00 INFO  done
Solution 10
POWERSHELL
$path = Join-Path ([System.IO.Path]::GetTempPath()) 'app.log'
@'
2025-03-01 10:00:01 INFO  start
2025-03-01 10:00:05 ERROR disk full
2025-03-01 10:01:00 WARN  slow query
2025-03-01 10:02:30 ERROR timeout
2025-03-01 10:03:00 INFO  done
'@ | Set-Content -Path $path

(Select-String -Path $path -Pattern 'ERROR').Count
Remove-Item $path

The answer is 2. Select-String returns one match object per matching line, so the count is the number of lines. Other valid answers: (Get-Content $path | Where-Object { $_ -match 'ERROR' }).Count or Get-Content $path | Select-String ERROR | Measure-Object. Wrapping the pipeline in parentheses and reading .Count also works when there is only one match, because PowerShell lets a single object answer .Count with 1.

11. A CSV round trip (Intermediate)

Create two objects with Name and Qty (a number), export them to a CSV file, import them again and print the type name of Qty after the round trip. What does that teach you?

Solution 11
POWERSHELL
$path = Join-Path ([System.IO.Path]::GetTempPath()) 'items.csv'
$items = @(
    [pscustomobject]@{ Name = 'bolt'; Qty = 40 }
    [pscustomobject]@{ Name = 'nut';  Qty = 25 }
)
$items | Export-Csv -Path $path -NoTypeInformation
$back = Import-Csv -Path $path

$items[0].Qty.GetType().Name     # Int32
$back[0].Qty.GetType().Name      # String
Remove-Item $path

Before: Int32. After: String. CSV is plain text and carries no type information, so every column comes back as a string. Convert what you need ([int]$row.Qty) right after importing. If you need types to survive, use JSON for numbers and booleans or Export-Clixml for full .NET objects.

12. A safe cleanup (Advanced)

Build a temporary folder with a.txt, c.tmp and a subfolder sub containing b.tmp. Delete every .tmp file in the tree, but first preview the deletion. Show the files that remain, then remove the folder.

Solution 12
POWERSHELL
$root = Join-Path ([System.IO.Path]::GetTempPath()) 'ex12'
New-Item -ItemType Directory -Path (Join-Path $root 'sub') -Force | Out-Null
'a' | Set-Content (Join-Path $root 'a.txt')
'c' | Set-Content (Join-Path $root 'c.tmp')
'b' | Set-Content (Join-Path $root 'sub\b.tmp')

$tmpFiles = Get-ChildItem -Path $root -Recurse -File -Filter *.tmp
$tmpFiles | Remove-Item -WhatIf      # preview only: nothing is deleted
$tmpFiles | Remove-Item              # the real deletion

Get-ChildItem -Path $root -Recurse -File | Select-Object -ExpandProperty Name   # a.txt
Remove-Item -Path $root -Recurse

-WhatIf prints what would happen (one line per file) and changes nothing. Always run it first when the command deletes or overwrites. The final listing shows only a.txt. Note -Filter *.tmp is applied by the file system provider and is faster than Where-Object for simple name patterns. On Linux or macOS use Join-Path $root 'sub' 'b.tmp' or forward slashes: \ is not a path separator there.

The JavaScript equivalent uses a small virtual file system (a Map from path to size) and a remove function with a whatIf option that mirrors the preview-then-delete habit.

JS Stand-in for exercises 10 to 12: files and data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the preview run leaves the file count at 3: nothing changed until the second remove call.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You import a CSV and run Sort-Object on a Size column, but 520 sorts after 50400. What is the most likely cause?

    Import-Csv and ConvertFrom-Csv produce string properties. Convert to a number type before sorting or comparing.
  2. 2. A function prints extra True and False lines. Which statement most likely causes it?

    Any value a statement produces goes to the output stream. Discard it with [void], $null = or Out-Null.
  3. 3. Get-Content on a missing file does not trigger your catch block. How do you fix it?

    The error is non-terminating. -ErrorAction Stop (or $ErrorActionPreference = 'Stop') makes it terminating so catch can handle it.
  4. 4. Which block runs whether or not an error occurred?

    finally always runs after try (and catch). Use it to clean up files, connections or temporary state.
  5. 5. What does -WhatIf do on Remove-Item?

    -WhatIf is a safety switch supported by cmdlets that change things. It reports the planned actions and skips them.

Summary

  • Imported data is text: cast to numbers or dates before sorting, comparing or summing.
  • Sort before Select-Object -First, and group with Group-Object plus Measure-Object for totals.
  • A function returns everything it outputs: discard stray results with [void] or $null =.
  • ValidateSet, Mandatory and ValueFromPipeline move input checking out of your function body.
  • -ErrorAction Stop makes non-terminating errors catchable; finally always runs.
  • Preview anything destructive with -WhatIf, and keep exercises inside a temporary folder.

Next, rehearse the theory with the PowerShell interview questions.