PowerShell Genie

PowerShell Functions

Return useful objects from a function and keep diagnostic messages out of its data stream.

Lesson 6 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Overview

A function groups a task behind a name and parameters. Get-DiskFreePercent accepts a drive letter, retrieves a volume and returns an object with Drive and FreePercent. Callers can filter, sort or export that object without parsing a sentence.

PowerShell emits unassigned expression results to the success stream. That includes a bare status string before the final object. Use Write-Verbose for diagnostic messages when you want the success stream to contain only report records.

return exits the current function scope and can emit a value. It does not discard output already written by earlier expressions. A function that writes a string and then returns an object has produced both.

The example assumes the volume query succeeds and Size is nonzero. Production code needs a decision for a missing drive, access failure and division by zero. Handle those cases explicitly before computing the percentage; do not convert every failure into a plausible zero percent.

Inspect this example’s structure

Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

Get-DiskFreePercent -Drive 'C'
  1. Stage 1Get-DiskFreePercent-Drive

    What happens

    Read Drive and FreePercent as separate properties. The displayed percentage is illustrative and depends on the real volume. When adapting the function, test a valid drive and a missing drive, and inspect the type of every returned record.

    Worth remembering

    A function’s contract includes its output type and failure behavior, not only its parameter names.

    Primary documentation

    Microsoft Learn: functions

    Learn this function the way you will use it

    Guided practice

    Work the same idea seven ways: understand it, predict the result, run it, inspect it, change it, debug it, then write your own. Your progress on this page is remembered on this device.

    1. Understand — name the idea once

      The same disk-space check copied into five scripts is five places to update when the rule changes, and five chances to drift apart. A function gives the idea a name (Get-DiskFreePercent), declares its input (-Drive, defaulting to 'C'), and keeps one place to fix. The lesson above showed the shape; the steps below make it stick.

    2. Predict — say what happens before it happens

      Reading code well means predicting before running. This call runs on a machine where drive C: has 48.2% free space:

      Get-DiskFreePercent -Drive 'C'

      What comes back?

    3. Run — watch the recorded example

      The lab on this page holds the function defined above, called with -Drive 'C'. Press the button to scroll to the lab and play its saved output. Nothing is executed in your browser — it is the recorded result of this exact example, against fictional volume data.

    4. Inspect — read the result like a debugger

    5. Modify — change the input, predict the change

      Same function, different drive. Both outputs below are recorded examples — sample output, not executed here.

      Drive C

      Get-DiskFreePercent -Drive 'C'

      Recorded output

      Drive  FreePercent
      -----  -----------
      C      48.2

      Drive D

      Get-DiskFreePercent -Drive 'D'

      Recorded output

      Drive  FreePercent
      -----  -----------
      D      71.9

      You change 'C' to 'D' and re-run. Select every true statement, then check.

    6. Solve independently — find the accidental output

      Someone edited the function and the Pester test started failing. Read it the way you would in a real review — no hints highlighted:

    7. Explain — write your own

      Write Get-VolumeLabel: a function that takes a drive letter (default 'C') and returns one object with Drive and Label properties. Assume Get-Volume -DriveLetter $Drive gives you .DriveLetter and .FileSystemLabel. Your draft stays on this page — nothing is sent anywhere.

      Tick every box that is true of your draft. Be honest — this checklist is the review:

      Keep going: the Pester lesson shows how to test a function like the one you just wrote — that is how you defend it in a review.

      Ready to prove it? Take the Functions capstone assessment: six checks, one attempt each, pass mark 5 of 6.

    Try it

    Illustrative output · values vary by environment

    1PS> function Get-DiskFreePercent {
    2PS> param([string] $Drive = 'C')
    3PS> $v = Get-Volume -DriveLetter $Drive
    4PS> [pscustomobject]@{
    5PS> Drive = $Drive
    6PS> FreePercent = [math]::Round($v.SizeRemaining / $v.Size * 100 , 1)
    7PS> } }
    8PS> Get-DiskFreePercent -Drive C

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    Run supported commands against the practice data, or inspect the example without executing it.

    Ready to inspect.

      Defines a function with one defaulted parameter and calls it.

      Show reference output

      Illustrative output · values vary by environment

      Drive  FreePercent
      -----  -----------
      C      48.2

      Practise this

      Create a service-report function

      Define Get-ServiceSummary to run the requested pipeline: Get-Service | Select-Object Name,Status. Call it and return its output.

      Review the lesson

      Keep going

      Next: PowerShell Scope

      Check your understanding

      A function prints a status string and then returns a report object. What reaches the caller?

      Genie guidePowerShell Functions

      Return useful objects from a function and keep diagnostic messages out of its data stream.