Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Functions · PowerShell Automation

Direct answer

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.

When to use this

Use this when organizing PowerShell code into functions.

First 30 seconds

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.

Operational verification

input → function → objects

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
PowerShell 7.5/current
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformPowerShell 7.5/current · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when organizing PowerShell code into functions.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Key points
  • Functions use a param() block.
  • Return objects, not formatted text.
  • Keep functions small and focused.
Key checks
  • Get-Command -CommandType Function — defined functions
  • Get-Help <function> — comment-based help
  • Invoke-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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
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
Technical examples

Configuration & expected output

Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.

Configuration example

PowerShell 7.5/current 7.5/currentMinimal authored PowerShell pattern for Functions

Assumptions: Review target identity, permissions and environment before mutation.

function Get-Square { param([int]$Number) $Number * $Number }
Get-Square -Number 4
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docPowerShell 7.5/current 7.5/current

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%
Embedded reference data

Quick lookup tables

Functions · PowerShell operational reference

Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.

BoundaryFunctions reference
Runtime identityPowerShell edition/version + command/module source
Persistent intentScript/module/config prerequisites under source control
VerificationRead-only discovery → execution evidence → independent target read-back
Output contractStructured objects/streams before formatting
Failure boundarySeparate engine/binding from transport/API/native and target-state failures
Depth when you need it

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.

Confirmation

Confirm action

Continue?