Use this when organizing PowerShell code into functions.
Functions · PowerShell Automation
PowerShell functions group reusable code with a name and param() block. Return objects rather than formatted text so the output can be piped and filtered.
1. Functions encapsulate logic.
2. Use param() blocks and comment-based help.
3. Output objects, not formatted text.
4. One responsibility each.
5. Test with Pester.
input → function → objects
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
Resolve the function with Get-Command, inspect its definition and parameter metadata, then test both direct and pipeline invocation when pipeline input is supported. Capture object types returned from the success stream and test error behavior with representative invalid inputs. For mutation, follow function output with independent target-state read-back.
Step 2 Common mistakes Narrow the fault
- Functions writing output unintentionally.
Step 3 Where it fails Narrow the fault
Function availability is scoped to the runspace/session and can differ after module import, dot-sourcing or remoting. Successful invocation does not show idempotency or target convergence. Distinguish command definition/scope, parameter binding, stream output and the external state the function intends to manage.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Functions use a param() block.
- Return objects, not formatted text.
- Keep functions small and focused.
Get-Command -CommandType Function— defined functionsGet-Help <function>— comment-based helpInvoke-Pester— tests
ReferenceWhy it matters1 section · depth on demand
In depth
Functions in PowerShell wrap reusable logic with named parameters. Everything a function outputs — not only what follows return — goes to the pipeline, which surprises people coming from other languages: stray output from commands inside the function becomes part of its result.
function Get-StaleComputer {
param([int]$Days = 90, [string]$SearchBase)
$cutoff = (Get-Date).AddDays(-$Days)
Get-ADComputer -Filter 'LastLogonTimeStamp -lt $cutoff' -SearchBase $SearchBase -Properties LastLogonTimeStamp |
Select-Object Name, @{n='LastLogon';e={[datetime]::FromFileTime($_.LastLogonTimeStamp)}}
}
Suppress unwanted output with $null = ... or [void], use approved verbs (Get-Verb) for discoverable names, and move functions into a module once more than one script uses them.
ReferenceImportant terms & boundaries1 section · depth on demand
PowerShell mechanics
A PowerShell function creates a command in session state. Ordinary functions can accept parameters and emit pipeline output; functions using begin, process, end and clean can process pipeline input with lifecycle semantics. Every unassigned expression or command result can contribute to success output, so incidental output inside a function is part of its observable contract unless suppressed.
ReferenceConfiguration & state1 section · depth on demand
Authoring and lifecycle
Keep functions small, parameter-driven and explicit about output types and side effects. Put reusable functions in modules rather than profiles, avoid hidden global state, and separate discovery/read functions from mutating actions where practical. When a function emits diagnostics, use the appropriate verbose/information/warning/error stream instead of contaminating the success stream.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Configuration & expected output
Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.
Configuration example
Assumptions: Review target identity, permissions and environment before mutation.
function Get-Square { param([int]$Number) $Number * $Number }
Get-Square -Number 4Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Microsoft Learn documentation reviewed for bounded PowerShell reference claims. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7.5 · confidence 94%Quick lookup tables
Functions · PowerShell operational reference
Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.
| Boundary | Functions reference |
|---|---|
| Runtime identity | PowerShell edition/version + command/module source |
| Persistent intent | Script/module/config prerequisites under source control |
| Verification | Read-only discovery → execution evidence → independent target read-back |
| Output contract | Structured objects/streams before formatting |
| Failure boundary | Separate engine/binding from transport/API/native and target-state failures |
Deep reference
Healthy vs suspicious evidence
Output interpretation
A function can appear to return one value while also emitting nested command output. Write-Host is presentation/information behavior, not structured return data. Pipeline input invokes process per item, while code outside the appropriate block may execute once, so count results and confirm object shape instead of judging only screen output.