PowerShell Functions
Return useful objects from a function and keep diagnostic messages out of its data stream.
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'- 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
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.
-
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. -
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?
-
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. -
Inspect — read the result like a debugger
-
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.2Drive D
Get-DiskFreePercent -Drive 'D'Recorded output
Drive FreePercent ----- ----------- D 71.9You change
'C'to'D'and re-run. Select every true statement, then check. -
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:
function Get-DiskFreePercent { param([string] $Drive = 'C') $v = Get-Volume -DriveLetter $Drive [pscustomobject]@{ Drive = $Drive FreePercent = [math]::Round($v.SizeRemaining / $v.Size * 100, 1) } }The fix is to delete line 4 — or capture it (
$bytesLeft = $v.SizeRemaining) if you need the value later. The rule to carry away: in PowerShell, any value you don't capture, redirect, or suppress becomes output — including a property read sitting alone on a line. -
Explain — write your own
Write
Get-VolumeLabel: a function that takes a drive letter (default'C') and returns one object withDriveandLabelproperties. AssumeGet-Volume -DriveLetter $Drivegives you.DriveLetterand.FileSystemLabel. Your draft stays on this page — nothing is sent anywhere.function Get-VolumeLabel { param([string] $Drive = 'C') $v = Get-Volume -DriveLetter $Drive [pscustomobject]@{ Drive = $Drive Label = $v.FileSystemLabel } }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
Example reader
Inspect this page's example
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.
The sandbox is visible now. Sign in with Google only when you run or check a task; commands and temporary files are discarded when you leave.
Run a command to inspect its result.
Inspect starting data
Supported syntax
Virtual files
Keep going
Next: PowerShell ScopeCheck your understanding
A function prints a status string and then returns a report object. What reaches the caller?
Both enter the success stream unless the status message uses a separate stream. Use Write-Verbose for diagnostics to keep the report pipeline consistent.