POWERSHELL / CHAPTER 06
Functions and clean output contracts
IntermediateReturn useful objects without leaking diagnostics into the data stream.
By the end of this chapter
- Declare named typed parameters
- Understand implicit success-stream output
- Separate diagnostics from returned data
The idea
A PowerShell function can emit multiple results even without a return statement. Any unassigned expression written to the success stream becomes part of its output. Return ends the current function or script block, but earlier output remains present. This differs from languages where one return expression is the only result channel, so inspect every statement that may emit a value.
Declare parameters with names, types, and validation appropriate to the contract. Use Write-Verbose for optional diagnostics instead of adding strings to the success stream of an object-producing function. Suppress unwanted method return values deliberately when necessary. A dependable function keeps its output shape consistent and lets callers decide whether to display, serialize, or further process the emitted records.
function Get-Double {
[CmdletBinding()]
param([Parameter(Mandatory)][int]$Value)
Write-Verbose "Doubling a value"
return $Value * 2
}
Get-Double -Value 48
The numeric result goes to the success stream. The diagnostic uses the verbose stream and is not included in the function’s ordinary captured result.
Try it yourself
Create a function returning a single summary object and send progress diagnostics only to the verbose stream.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING