Functions and Advanced Functions

Write PowerShell functions that behave like real cmdlets: typed and validated parameters, pipeline input, -WhatIf and -Confirm support, and help that Get-Help can show.

By The Dark DebuggerUpdated 30 min read

This article takes you from a five-line function to an advanced function that validates its input, accepts pipeline objects, supports -WhatIf, -Confirm and -Verbose, and documents itself for Get-Help. It assumes you're comfortable with loops, the pipeline and custom objects. The next article, scripts, scope, and modules, shows how to package these functions so other scripts and people can use them.

Why functions, and why "advanced" ones

Picture a deployment script that has grown to 400 lines. The block that deletes old release folders has been pasted into three places, and one copy was "fixed" last month while the other two weren't. Nobody dares run the script by hand because there's no dry-run mode. When someone passes -Keep 0 by mistake, it happily deletes every release.

Functions fix the duplication. Advanced functions fix the rest. Add one attribute, [CmdletBinding()], plus a few parameter attributes, and PowerShell gives your function the same behaviour as a built-in cmdlet: argument validation with clear error messages, -Verbose output, -WhatIf dry runs, confirmation prompts, pipeline binding and help text. You write very little code for any of it.

Every example below was saved as a .ps1 file and run with pwsh -NoProfile -File on PowerShell 7.6.9, in a folder containing a few application logs and a releases folder. Error messages therefore show a script path and line number. At an interactive prompt you get a shorter one-line version.

A simple function

A function is a named script block. The param() block declares its parameters, and anything the body outputs becomes the function's result:

function Get-LogSummary {
    param($Path)
 
    $lines = Get-Content -Path $Path
    [pscustomobject]@{
        File   = Split-Path -Path $Path -Leaf
        Lines  = $lines.Count
        Errors = ($lines -match ' (ERROR|FATAL) ').Count
    }
}
 
Get-LogSummary -Path ./logs/api.log
Get-LogSummary ./logs/billing.log
File        Lines Errors
----        ----- ------
api.log       420     10
billing.log   260     18

The function returns an object, not formatted text, so its output can be sorted, filtered or exported like any cmdlet's. Make that a habit from your first function.

Name functions Verb-Noun with a singular noun, using one of PowerShell's approved verbs. Get-Verb lists them:

Get-Verb -Verb Get, Set, New, Remove, Invoke, Test | Format-Table -Property Verb, Group
Verb   Group
----   -----
Get    Common
New    Common
Remove Common
Set    Common
Test   Diagnostic
Invoke Lifecycle

This isn't just style. When you put functions with unapproved verbs (Delete-, Check-, Fetch-) into a module, Import-Module prints a warning every time it loads. Use Remove, Test and Get instead.

Calling functions: spaces, not commas

PowerShell commands take arguments separated by spaces, by name or by position. The habit from other languages, Name(a, b), does something different:

function Get-Sum {
    param([int]$First, [int]$Second)
    "First=$First Second=$Second Sum=$($First + $Second)"
}
 
Get-Sum 2 3
Get-Sum -First 2 -Second 3
Get-Sum(2, 3)
First=2 Second=3 Sum=5
First=2 Second=3 Sum=5
Get-Sum: /home/sid/functions/call-gotcha.ps1:8
Line |
   8 |  Get-Sum(2, 3)
     |         ~~~~~~
     | Cannot process argument transformation on parameter 'First'. Cannot
     | convert the "System.Object[]" value of type "System.Object[]" to type
     | "System.Int32".

(2, 3) is a single argument, an array, and it went to -First. Without the [int] type on the parameter there would be no error at all, just a wrong result. Use named arguments in scripts. They survive parameter reordering and make the call self-documenting.

Parameter types and defaults

Give every parameter a type and, where it makes sense, a default. The type converts what it can and rejects what it can't, before your code runs:

function Get-OldLog {
    param(
        [string]$Path = './logs',
        [int]$Days = 7,
        [string[]]$Extension = @('.log', '.txt')
    )
    "Path=$Path Days=$Days Extension=$($Extension -join ',')"
}
 
Get-OldLog
Get-OldLog -Days 30 -Extension .gz
Get-OldLog -Days '14'
Get-OldLog -Days ten
Path=./logs Days=7 Extension=.log,.txt
Path=./logs Days=30 Extension=.gz
Path=./logs Days=14 Extension=.log,.txt
Get-OldLog: /home/sid/functions/typed.ps1:13
Line |
  13 |  Get-OldLog -Days ten
     |                   ~~~
     | Cannot process argument transformation on parameter 'Days'. Cannot
     | convert value "ten" to type "System.Int32". Error: "The input string
     | 'ten' was not in a correct format."

The string '14' was converted to 14. A single .gz was wrapped into a one-element [string[]], so callers can pass one value or many. ten failed with an error that names the parameter. That beats a confusing failure 30 lines into the function.

Mandatory parameters

[Parameter(Mandatory)] makes PowerShell refuse to run the function without the value. For a [string] it also rejects $null and empty strings:

function Remove-Release {
    param(
        [Parameter(Mandatory, HelpMessage = 'Release folder name, e.g. 2026-11-01')]
        [string]$Name
    )
    "Would remove release $Name"
}
 
Remove-Release -Name 2026-11-01
Remove-Release -Name ''
Remove-Release

What happens on the last line depends on whether anyone can answer. I ran the script with 2026-10-05 piped to its standard input, which stands in for a person typing it:

Would remove release 2026-11-01
Remove-Release: /home/sid/functions/mandatory.ps1:10
Line |
  10 |  Remove-Release -Name ''
     |                       ~~
     | Cannot bind argument to parameter 'Name' because it is an empty string.
 
cmdlet Remove-Release at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
Name: 2026-10-05
Would remove release 2026-10-05

Typing !? at that prompt shows the HelpMessage. Running the same script with pwsh -NonInteractive, as a scheduled task or CI job should, turns the prompt into an immediate error:

Remove-Release: /home/sid/functions/mandatory.ps1:11
Line |
  11 |  Remove-Release
     |  ~~~~~~~~~~~~~~
     | Cannot process command because of one or more missing mandatory
     | parameters: Name.

That's the behaviour you want in automation: fail fast instead of hanging forever on a prompt nobody will see. Always start unattended PowerShell with -NonInteractive.

Output: everything is returned

This is the single most surprising thing about PowerShell functions. Every value the body produces and doesn't capture becomes output, not just what you return. return only means "stop here, and output this too". Here's the bug in its natural habitat:

function New-ReleaseFolder {
    param([string]$Name)
 
    $log = [System.Collections.ArrayList]::new()
    $log.Add("creating $Name")
    New-Item -ItemType Directory -Path "./staging/$Name" -Force
    return "./staging/$Name"
}
 
$path = New-ReleaseFolder -Name 2026-11-09
"Count: $($path.Count)"
$path | ForEach-Object { $_.GetType().Name }
Count: 3
Int32
DirectoryInfo
String

The caller expected one path string and got three things. ArrayList.Add() returns the index of the new item (0). New-Item returns the DirectoryInfo it created. Only then comes the string. Code that does Join-Path $path 'VERSION' will now fail in a confusing way, far from the cause.

The fix is to discard anything you don't want returned. $null = … is the clearest and fastest; [void](…) and | Out-Null also work. Better still, use List[T], whose .Add() returns nothing:

function New-ReleaseFolder {
    param([string]$Name)
 
    $log = [System.Collections.Generic.List[string]]::new()
    $log.Add("creating $Name")
    $null = New-Item -ItemType Directory -Path "./staging/$Name" -Force
    "./staging/$Name"
}
 
$path = New-ReleaseFolder -Name 2026-11-09
"Count: $($path.Count)"
$path
Count: 1
./staging/2026-11-09

Two related rules come from the same design. First, arrays are unrolled on the way out, so a one-element array arrives as a plain value. Use Write-Output -NoEnumerate, or have the caller wrap the call in @():

function Get-WebServer {
    $servers = @('web01')
    return $servers
}
function Get-WebServerArray {
    $servers = @('web01')
    Write-Output -InputObject $servers -NoEnumerate
}
 
(Get-WebServer).GetType().Name
(Get-WebServerArray).GetType().Name
@(Get-WebServer).GetType().Name
String
Object[]
Object[]

Windows PowerShell 5.1 is different here. The same script printed String, String, Object[], so -NoEnumerate had no effect. The form that works in both versions is the unary comma, which wraps the array in a one-element array that gets unrolled instead:

function Get-WebServerComma {
    $servers = @('web01')
    return , $servers
}
(Get-WebServerComma).GetType().Name
Object[]

That printed Object[] on both 7.6.9 and 5.1. In practice, wrapping at the call site (@(Get-WebServer)) is the most robust habit, because it doesn't depend on how the function was written.

Second, Write-Host is not output. It writes straight to the screen, so the caller can't capture it:

function Get-Greeting {
    param([string]$Name)
    Write-Host "Hello, $Name"
}
 
$greeting = Get-Greeting -Name 'ops'
"Captured: [$greeting]"
Hello, ops
Captured: []

Pick the stream that matches the intent:

CommandGoes toUse it for
a bare value, or Write-OutputOutput (stream 1), returned to the callerThe function's results, ideally objects
return $xOutput, then exits the functionEarly exit. Not needed for the final value
Write-VerboseVerbose stream, hidden unless -Verbose"What am I doing" messages for troubleshooting
Write-WarningWarning stream, shown by defaultSomething odd that doesn't stop the work
Write-ErrorError streamA failure for one item. See error handling
Write-HostThe console onlyInteractive menus or colour. Never for data

Advanced functions: [CmdletBinding()]

Put [CmdletBinding()] above param() and the function becomes an advanced function. Here is a health check with one mandatory parameter, one optional one, and some Write-Verbose calls:

function Test-LogHealth {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path,
 
        [int]$MaxErrors = 5
    )
 
    Write-Verbose "Reading $Path"
    $errors = (Select-String -Path $Path -Pattern ' (ERROR|FATAL) ').Count
    Write-Verbose "Found $errors error lines (limit $MaxErrors)"
 
    [pscustomobject]@{
        Log     = Split-Path -Path $Path -Leaf
        Errors  = $errors
        Healthy = $errors -le $MaxErrors
    }
}

With the function defined, a normal call is quiet:

Test-LogHealth -Path ./logs/auth.log
Log      Errors Healthy
---      ------ -------
auth.log      1    True

-Verbose switches on the diagnostic messages without any extra code:

Test-LogHealth -Path ./logs/api.log -Verbose
VERBOSE: Reading ./logs/api.log
VERBOSE: Found 10 error lines (limit 5)
 
Log     Errors Healthy
---     ------ -------
api.log     10   False

A misspelled parameter name is rejected:

Test-LogHealth -Path ./logs/api.log -MaxErrrors 20
Test-LogHealth: /home/sid/functions/cb3.ps1:2
Line |
   2 |  Test-LogHealth -Path ./logs/api.log -MaxErrrors 20
     |                                      ~~~~~~~~~~~
     | A parameter cannot be found that matches parameter name 'MaxErrrors'.

That error is a bigger deal than it looks. A simple function, one without [CmdletBinding()], quietly puts unknown arguments into the automatic $args variable:

function Test-LogHealthSimple {
    param([string]$Path, [int]$MaxErrors = 5)
    "MaxErrors is $MaxErrors; leftover arguments: $args"
}
 
Test-LogHealthSimple -Path ./logs/api.log -MaxErrrors 20
MaxErrors is 5; leftover arguments: -MaxErrrors 20

The caller asked for a limit of 20 and silently got 5. For this reason alone I put [CmdletBinding()] on every function longer than a few lines.

The attribute also adds the common parameters. You can see them on the command:

function Test-LogHealth {
    [CmdletBinding()]
    param([string]$Path, [int]$MaxErrors = 5)
}
(Get-Command -Name Test-LogHealth).Parameters.Keys -join ', '
Path, MaxErrors, Verbose, Debug, ErrorAction, WarningAction, InformationAction, ProgressAction, ErrorVariable, WarningVariable, InformationVariable, OutVariable, OutBuffer, PipelineVariable

-ErrorAction and -ErrorVariable now work on your function exactly as they do on Get-Item. ProgressAction appeared in PowerShell 7.4. On 5.1, the same command listed everything except ProgressAction. Inside an advanced function you also get $PSCmdlet, the object that powers -WhatIf below.

Validating parameters

Validation attributes check arguments before the body runs, and they produce consistent, specific error messages for free. These are the four you'll use most:

function New-AppDeployment {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('dev', 'staging', 'prod')]
        [string]$Environment,
 
        [ValidateRange(1, 20)]
        [int]$Replicas = 2,
 
        [ValidatePattern('^\d+\.\d+\.\d+$')]
        [string]$Version = '1.0.0',
 
        [ValidateScript({ Test-Path -Path $_ -PathType Leaf })]
        [string]$ConfigFile
    )
    "Deploying $Version to $Environment with $Replicas replicas"
}
 
New-AppDeployment -Environment staging -Replicas 3 -Version 2.4.1
New-AppDeployment -Environment production
New-AppDeployment -Environment prod -Replicas 50
New-AppDeployment -Environment prod -Version 2.4
New-AppDeployment -Environment prod -ConfigFile ./deploy/prod.json
New-AppDeployment -Environment PROD
Deploying 2.4.1 to staging with 3 replicas
New-AppDeployment: /home/sid/functions/validation.ps1:21
Line |
  21 |  New-AppDeployment -Environment production
     |                                 ~~~~~~~~~~
     | Cannot validate argument on parameter 'Environment'. The argument
     | "production" does not belong to the set "dev,staging,prod" specified by
     | the ValidateSet attribute. Supply an argument that is in the set and
     | then try the command again.
New-AppDeployment: /home/sid/functions/validation.ps1:22
Line |
  22 |  New-AppDeployment -Environment prod -Replicas 50
     |                                                ~~
     | Cannot validate argument on parameter 'Replicas'. The 50 argument is
     | greater than the maximum allowed range of 20. Supply an argument that is
     | less than or equal to 20 and then try the command again.
New-AppDeployment: /home/sid/functions/validation.ps1:23
Line |
  23 |  New-AppDeployment -Environment prod -Version 2.4
     |                                               ~~~
     | Cannot validate argument on parameter 'Version'. The argument "2.4" does
     | not match the "^\d+\.\d+\.\d+$" pattern. Supply an argument that matches
     | "^\d+\.\d+\.\d+$" and try the command again.
New-AppDeployment: /home/sid/functions/validation.ps1:24
Line |
  24 |  New-AppDeployment -Environment prod -ConfigFile ./deploy/prod.json
     |                                                  ~~~~~~~~~~~~~~~~~~
     | Cannot validate argument on parameter 'ConfigFile'. The " Test-Path
     | -Path $_ -PathType Leaf " validation script for the argument with value
     | "./deploy/prod.json" did not return a result of True. Determine why the
     | validation script failed, and then try the command again.
Deploying 1.0.0 to PROD with 2 replicas

Notice the last line: ValidateSet is case-insensitive, so PROD passed, but the variable keeps the caller's spelling. If later code does if ($Environment -ceq 'prod') or builds a case-sensitive path on Linux, PROD slips through. Normalise with $Environment = $Environment.ToLower() when the case matters. ValidateSet also gives you tab completion of the allowed values at the prompt.

The ValidatePattern and ValidateScript messages are written for the function's author, not its user. Since PowerShell 6 both accept an ErrorMessage, where {0} is the rejected value:

function New-AppDeployment {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('dev', 'staging', 'prod')]
        [string]$Environment,
 
        [ValidatePattern('^\d+\.\d+\.\d+$',
            ErrorMessage = '"{0}" is not a semantic version like 2.4.1')]
        [string]$Version = '1.0.0',
 
        [ValidateScript({ Test-Path -Path $_ -PathType Leaf },
            ErrorMessage = 'Config file {0} does not exist')]
        [string]$ConfigFile
    )
    "Deploying $Version to $Environment"
}
 
New-AppDeployment -Environment prod -Version 2.4
New-AppDeployment -Environment prod -ConfigFile ./deploy/prod.json
New-AppDeployment: /home/sid/functions/validation-messages.ps1:19
Line |
  19 |  New-AppDeployment -Environment prod -Version 2.4
     |                                               ~~~
     | Cannot validate argument on parameter 'Version'. "2.4" is not a semantic
     | version like 2.4.1
New-AppDeployment: /home/sid/functions/validation-messages.ps1:20
Line |
  20 |  New-AppDeployment -Environment prod -ConfigFile ./deploy/prod.json
     |                                                  ~~~~~~~~~~~~~~~~~~
     | Cannot validate argument on parameter 'ConfigFile'. Config file
     | ./deploy/prod.json does not exist

ErrorMessage does not exist in Windows PowerShell 5.1. There, defining the function fails with Property 'ErrorMessage' cannot be found for type 'System.Management.Automation.ValidatePatternAttribute'. A function that has to run on 5.1 has to live with the default wording, or check inside the body and throw its own message.

AttributeChecksExample
ValidateSetValue is one of a fixed list (case-insensitive)[ValidateSet('dev','prod')]
ValidateRangeNumber within bounds. 7.x also accepts 'Positive', 'NonNegative'[ValidateRange(1, 20)]
ValidatePatternString matches a regex[ValidatePattern('^[a-z0-9-]+$')]
ValidateScriptScript block returns $true ($_ is the value)[ValidateScript({ Test-Path $_ })]
ValidateLengthString length within bounds[ValidateLength(3, 63)]
ValidateCountNumber of array elements within bounds[ValidateCount(1, 10)]
ValidateNotNullOrEmptyNot $null, '' or an empty arrayfor optional parameters

Switch parameters

A [switch] is an on/off flag. It's $false unless the caller includes it:

function Clear-TempFile {
    [CmdletBinding()]
    param(
        [string]$Path = './tmp',
        [switch]$Recurse
    )
    "Recurse is $Recurse (type $($Recurse.GetType().Name)); IsPresent = $($Recurse.IsPresent)"
}
 
Clear-TempFile
Clear-TempFile -Recurse
Clear-TempFile -Recurse:$false
Recurse is False (type SwitchParameter); IsPresent = False
Recurse is True (type SwitchParameter); IsPresent = True
Recurse is False (type SwitchParameter); IsPresent = False

Test it with a plain if ($Recurse). The -Name:$value colon syntax lets a wrapper pass its own switch through (-Recurse:$Recurse). Don't give a switch a default of $true. Callers would then need -Recurse:$false to turn it off, which nobody expects. If you want something on by default, name the switch for the opposite, as in -NoRecurse.

Pipeline input: begin, process, end

To accept pipeline input, mark a parameter ValueFromPipeline and put the per-item code in a process block. PowerShell runs process once for each incoming object:

function ConvertTo-Kilobyte {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [long]$Bytes
    )
    process {
        [math]::Round($Bytes / 1KB, 1)
    }
}
 
30679, 13268, 113941 | ConvertTo-Kilobyte
30
13
111.3

Leave out the process block and the body runs once, after all input has been bound, so the parameter only holds the last item:

function ConvertTo-Kilobyte {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [long]$Bytes
    )
    [math]::Round($Bytes / 1KB, 1)
}
 
30679, 13268, 113941 | ConvertTo-Kilobyte
111.3

No error, two results silently lost. If a function takes pipeline input, it needs a process block.

ValueFromPipelineByPropertyName is often more useful: it binds a parameter from the property of the same name on each incoming object. Add [Alias()] to accept other property names too. Here -Path accepts the FullName property that Get-ChildItem objects carry, and begin and end run once around the whole stream:

function Measure-LogFile {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias('FullName')]
        [string]$Path
    )
 
    begin {
        Write-Verbose 'begin: runs once, before the first input object'
        $totalErrors = 0
    }
    process {
        $errors = (Select-String -Path $Path -Pattern ' (ERROR|FATAL) ').Count
        $totalErrors += $errors
        '{0,-12} {1,3} errors' -f (Split-Path -Path $Path -Leaf), $errors
    }
    end {
        Write-Verbose "end: runs once, after the last object ($totalErrors errors in total)"
    }
}
 
Get-ChildItem -Path ./logs -Filter *.log | Measure-LogFile -Verbose
'---'
Measure-LogFile -Path ./logs/auth.log
VERBOSE: begin: runs once, before the first input object
api.log       10 errors
auth.log       1 errors
billing.log   18 errors
VERBOSE: end: runs once, after the last object (29 errors in total)
---
auth.log       1 errors

The same function works with a direct -Path argument, in which case process runs once. Property binding is also how CSV files flow straight into functions. Every column becomes a property:

@'
ComputerName,Port,Role
web01,443,frontend
web02,443,frontend
db01,5432,database
'@ | Set-Content -Path ./hosts.csv
 
function Get-Endpoint {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias('Server', 'HostName')]
        [string]$ComputerName,
 
        [Parameter(ValueFromPipelineByPropertyName)]
        [int]$Port = 80
    )
    process {
        '{0}:{1}' -f $ComputerName, $Port
    }
}
 
Import-Csv -Path ./hosts.csv | Get-Endpoint
[pscustomobject]@{ Server = 'cache01' } | Get-Endpoint
web01:443
web02:443
db01:5432
cache01:80

The CSV's Role column was ignored because no parameter wanted it. The last object had a Server property, which matched the alias, and no Port, so the default applied. The Port values arrived from the CSV as strings and were converted to [int] by the parameter type.

-WhatIf and -Confirm: SupportsShouldProcess

Any function that changes something (deletes, restarts, writes) should support a dry run. Declare SupportsShouldProcess and wrap each change in $PSCmdlet.ShouldProcess(target, action). That method returns $false under -WhatIf, after printing what would have happened. It asks the user under -Confirm, and returns $true otherwise:

function Remove-OldRelease {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [string]$Path = './releases',
 
        [ValidateRange(1, 50)]
        [int]$Keep = 3
    )
 
    $releases = Get-ChildItem -Path $Path -Directory | Sort-Object -Property Name -Descending
    foreach ($dir in $releases | Select-Object -Skip $Keep) {
        if ($PSCmdlet.ShouldProcess($dir.Name, 'Delete release folder')) {
            Remove-Item -Path $dir.FullName -Recurse
            Write-Verbose "Deleted $($dir.Name)"
        }
    }
}
 
Remove-OldRelease -Keep 3 -WhatIf
'---'
Remove-OldRelease -Keep 3 -Confirm:$false -Verbose
'---'
(Get-ChildItem -Path ./releases -Directory).Name
What if: Performing the operation "Delete release folder" on target "2026-10-05".
What if: Performing the operation "Delete release folder" on target "2026-09-28".
What if: Performing the operation "Delete release folder" on target "2026-09-14".
---
VERBOSE: Performing the operation "Delete release folder" on target "2026-10-05".
VERBOSE: Deleted 2026-10-05
VERBOSE: Performing the operation "Delete release folder" on target "2026-09-28".
VERBOSE: Deleted 2026-09-28
VERBOSE: Performing the operation "Delete release folder" on target "2026-09-14".
VERBOSE: Deleted 2026-09-14
---
2026-10-19
2026-11-02
2026-11-09

ConfirmImpact decides when PowerShell asks without being told to. The session's $ConfirmPreference defaults to High, so a High-impact function prompts on every call unless the caller passes -Confirm:$false. Use High for operations that are hard to undo, and leave the default (Medium) for routine changes. This is the prompt, which I answered with N. Nothing was deleted:

Confirm
Are you sure you want to perform this action?
Performing the operation "Delete release folder" on target "2026-09-14".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help 
(default is "Y"):N

-WhatIf and -Confirm also flow into the cmdlets your function calls. Under -WhatIf, a Remove-Item inside the function would have printed its own "What if" line instead of deleting, even without the ShouldProcess check. Don't rely on that, though. The check is what makes the output readable ("Delete release folder" rather than a raw path), and it's the only thing that protects non-cmdlet code. The first common mistake below shows what happens without it.

Comment-based help

A comment block with keywords like .SYNOPSIS and .EXAMPLE, placed at the top of the function body (or just above function), becomes help that Get-Help displays like a built-in cmdlet's. Here is the release cleaner with its help (body omitted for now):

function Remove-OldRelease {
    <#
    .SYNOPSIS
    Deletes old release folders, keeping the newest ones.
 
    .DESCRIPTION
    Sorts the release folders under -Path by name (release folders are named
    yyyy-MM-dd, so name order is date order) and deletes all but the newest
    -Keep folders. Supports -WhatIf and -Confirm.
 
    .PARAMETER Path
    Folder that contains one sub-folder per release.
 
    .PARAMETER Keep
    How many of the newest releases to keep. Between 1 and 50.
 
    .EXAMPLE
    Remove-OldRelease -Path /srv/app/releases -Keep 5 -WhatIf
 
    Shows which release folders would be deleted, without deleting anything.
 
    .OUTPUTS
    None. Use -Verbose to see each deleted folder.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [string]$Path = './releases',
 
        [ValidateRange(1, 50)]
        [int]$Keep = 3
    )
}
Get-Help -Name Remove-OldRelease
NAME
    Remove-OldRelease
    
SYNOPSIS
    Deletes old release folders, keeping the newest ones.
    
    
SYNTAX
    Remove-OldRelease [[-Path] <String>] [[-Keep] <Int32>] [-WhatIf] [-Confirm]
     [<CommonParameters>]
    
    
DESCRIPTION
    Sorts the release folders under -Path by name (release folders are named
    yyyy-MM-dd, so name order is date order) and deletes all but the newest
    -Keep folders. Supports -WhatIf and -Confirm.
    
 
RELATED LINKS
 
REMARKS
    To see the examples, type: "Get-Help Remove-OldRelease -Examples"
    For more information, type: "Get-Help Remove-OldRelease -Detailed"
    For technical information, type: "Get-Help Remove-OldRelease -Full"

The SYNTAX section is generated from the param() block, so it can't drift out of date. Help for one parameter, and the examples:

Get-Help -Name Remove-OldRelease -Parameter Keep
-Keep <Int32>
    How many of the newest releases to keep. Between 1 and 50.
    
    Required?                    false
    Position?                    2
    Default value                3
    Accept pipeline input?       false
    Aliases                      
    Accept wildcard characters?  false
Get-Help -Name Remove-OldRelease -Examples
NAME
    Remove-OldRelease
    
SYNOPSIS
    Deletes old release folders, keeping the newest ones.
    
    
    -------------------------- EXAMPLE 1 --------------------------
    
    PS > Remove-OldRelease -Path /srv/app/releases -Keep 5 -WhatIf
    
    Shows which release folders would be deleted, without deleting anything.

Two things can silently break comment-based help. A misspelled keyword (.PARAMATER) makes PowerShell ignore the entire block, and so does more than one blank line between the help block and function when the block sits above it. If Get-Help shows only the auto-generated syntax, check those first.

While testing I hit a display quirk worth knowing. When one script outputs several Get-Help results in a row, PowerShell formats them all with the first one's layout, so -Examples looked exactly like the default view. Run each Get-Help as its own command, as above, or pipe it to Out-String.

Where you'll use this

Advanced functions are how PowerShell automation gets shared and trusted:

  • Deployment and maintenance tooling. Pruning releases, rotating logs, recycling app pools. -WhatIf lets a reviewer see exactly what a change will do before it runs in production.
  • Wrappers around REST APIs. Get-Ticket, New-DnsRecord, Set-FeatureFlag, with ValidateSet for environments, Mandatory for IDs, and pipeline input so you can write Import-Csv records.csv | New-DnsRecord.
  • Inventory and reporting. Functions that take -ComputerName by property name and emit objects that end up in Export-Csv.
  • Team modules. Every function in a shared module should be advanced, with help, so colleagues can use it from Get-Help without reading the source.

Here's the complete release cleaner: the help from above plus a body that handles the "nothing to do" case. In a real deployment it lives in a module (next article) and runs after each successful deploy:

function Remove-OldRelease {
    <#
    .SYNOPSIS
    Deletes old release folders, keeping the newest ones.
 
    .DESCRIPTION
    Sorts the release folders under -Path by name (release folders are named
    yyyy-MM-dd, so name order is date order) and deletes all but the newest
    -Keep folders. Supports -WhatIf and -Confirm.
 
    .PARAMETER Path
    Folder that contains one sub-folder per release.
 
    .PARAMETER Keep
    How many of the newest releases to keep. Between 1 and 50.
 
    .EXAMPLE
    Remove-OldRelease -Path /srv/app/releases -Keep 5 -WhatIf
 
    Shows which release folders would be deleted, without deleting anything.
 
    .OUTPUTS
    None. Use -Verbose to see each deleted folder.
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [string]$Path = './releases',
 
        [ValidateRange(1, 50)]
        [int]$Keep = 3
    )
 
    $releases = Get-ChildItem -Path $Path -Directory | Sort-Object -Property Name -Descending
    if ($releases.Count -le $Keep) {
        Write-Verbose "Only $($releases.Count) release(s) in $Path; nothing to delete"
        return
    }
 
    foreach ($dir in $releases | Select-Object -Skip $Keep) {
        if ($PSCmdlet.ShouldProcess($dir.Name, 'Delete release folder')) {
            Remove-Item -LiteralPath $dir.FullName -Recurse -Force
            Write-Verbose "Deleted $($dir.Name)"
        }
    }
}

The function was saved as Remove-OldRelease.ps1 and loaded into a fresh session, then used the way a deploy pipeline would use it: list, dry run, real run, and a second real run to prove it is safe to repeat:

. ./Remove-OldRelease.ps1
 
(Get-ChildItem -Path ./releases -Directory).Name -join ' '
Remove-OldRelease -Path ./releases -Keep 4 -WhatIf
Remove-OldRelease -Path ./releases -Keep 4 -Confirm:$false -Verbose
Remove-OldRelease -Path ./releases -Keep 4 -Confirm:$false -Verbose
(Get-ChildItem -Path ./releases -Directory).Name -join ' '
2026-09-14 2026-09-28 2026-10-05 2026-10-19 2026-11-02 2026-11-09
What if: Performing the operation "Delete release folder" on target "2026-09-28".
What if: Performing the operation "Delete release folder" on target "2026-09-14".
VERBOSE: Performing the operation "Delete release folder" on target "2026-09-28".
VERBOSE: Deleted 2026-09-28
VERBOSE: Performing the operation "Delete release folder" on target "2026-09-14".
VERBOSE: Deleted 2026-09-14
VERBOSE: Only 4 release(s) in ./releases; nothing to delete
2026-10-05 2026-10-19 2026-11-02 2026-11-09

The leading . (dot-sourcing) loads the function into the current session. The next article explains it. -LiteralPath protects against folder names containing [ or ], which -Path would treat as wildcard characters. -Keep 0 is impossible thanks to ValidateRange, which was the accident from the opening scenario.

Common mistakes

Declaring SupportsShouldProcess but never calling ShouldProcess

The attribute adds -WhatIf to the function's parameters. It does not make the function honour it. This version deletes with a .NET method, which knows nothing about -WhatIf:

function Remove-OldRelease {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Path = './releases', [int]$Keep = 3)
 
    $releases = Get-ChildItem -Path $Path -Directory | Sort-Object -Property Name -Descending
    foreach ($dir in $releases | Select-Object -Skip $Keep) {
        [System.IO.Directory]::Delete($dir.FullName, $true)
    }
}
 
(Get-ChildItem -Path ./releases -Directory).Count
Remove-OldRelease -Keep 1 -WhatIf
(Get-ChildItem -Path ./releases -Directory).Count
6
1

The dry run deleted five releases and printed nothing. A -WhatIf that lies is worse than none, because people trust it. Every state-changing line must sit inside if ($PSCmdlet.ShouldProcess(...)).

ConfirmImpact High in a scheduled job

A function with ConfirmImpact = 'High' prompts by default. Run from a scheduled task or CI job with -NonInteractive, the prompt can't be shown, and the call fails:

MethodInvocationException: /home/sid/functions/shouldprocess-noninteractive.ps1:7
Line |
   7 |          if ($PSCmdlet.ShouldProcess($dir.Name, 'Delete release folder …
     |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "ShouldProcess" with "2" argument(s): "PowerShell is
     | in NonInteractive mode. Read and Prompt functionality is not available."

Without -NonInteractive and with no input available, I got a different symptom: the prompt was printed and the call died with Object reference not set to an instance of an object. Either way the fix is the same. Automation must pass -Confirm:$false explicitly, which also documents that the unattended deletion is intended.

Forgetting the process block

Shown above: a pipeline function without process { } processes only the last input object, with no error. If ValueFromPipeline or ValueFromPipelineByPropertyName appears in the param() block, a process block must appear in the body.

Leaking values into the output

$list.Add(), New-Item, mkdir, $hashtable.Remove()-style calls that return something, and stray expressions all end up in the function's output. When a caller gets "an array when I expected a string", look for uncaptured values first and assign them to $null.

Summary

  • Name functions Verb-Noun with approved verbs, give every parameter a type, and output objects rather than formatted text.
  • Call functions with spaces and named parameters: Get-Sum -First 2 -Second 3. Get-Sum(2, 3) passes one array.
  • Everything a function body outputs is returned, not just return. Discard noise with $null = …. One-element arrays are unrolled. return , $array prevents that in every version (Write-Output -NoEnumerate only works in 7), and callers can always wrap the call in @().
  • [CmdletBinding()] adds -Verbose, -ErrorAction and the other common parameters, and rejects misspelled parameter names that a simple function would quietly drop into $args.
  • Mandatory, ValidateSet, ValidateRange, ValidatePattern and ValidateScript reject bad input before your code runs. ErrorMessage (7.x only) makes the errors readable. ValidateSet is case-insensitive and keeps the caller's casing.
  • Pipeline parameters need a process block. ValueFromPipelineByPropertyName plus [Alias()] lets objects from Get-ChildItem or Import-Csv bind by property name.
  • SupportsShouldProcess only works if every change is wrapped in $PSCmdlet.ShouldProcess(). ConfirmImpact = 'High' prompts by default, so automation must pass -Confirm:$false.
  • Comment-based help (.SYNOPSIS, .PARAMETER, .EXAMPLE) makes Get-Help work for your function. One misspelled keyword disables the whole block.

Exercises

Exercise 1: A pipeline-friendly convertereasy

Write ConvertTo-Celsius, which takes -Fahrenheit (a [double]) either as a parameter or from the pipeline, and outputs the Celsius value rounded to one decimal place. Test it with 32, 98.6, 212 | ConvertTo-Celsius and ConvertTo-Celsius -Fahrenheit 451.

Show Solution
function ConvertTo-Celsius {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [double]$Fahrenheit
    )
    process {
        [math]::Round(($Fahrenheit - 32) * 5 / 9, 1)
    }
}
 
32, 98.6, 212 | ConvertTo-Celsius
ConvertTo-Celsius -Fahrenheit 451
0
37
100
232.8

Without the process block, the pipeline call would print only 100.

Exercise 2: Fix the leaky functioneasy

This function should return the number of ERROR lines in a log. Run it against ./logs/auth.log, explain the output, and fix it so $count is a single number and the "Scanned" message only appears with -Verbose.

function Get-ErrorCount {
    param([string]$Path)
    $errorLines = [System.Collections.ArrayList]::new()
    foreach ($line in Get-Content -Path $Path) {
        if ($line -match ' ERROR ') { $errorLines.Add($line) }
    }
    Write-Host "Scanned $Path"
    return $errorLines.Count
}
 
$count = Get-ErrorCount -Path ./logs/auth.log
"count = $count"
Scanned ./logs/auth.log
count = 0 1
Show Solution

ArrayList.Add() returned the index 0 for the one error line it added, and that leaked into the output ahead of the real count, so $count is the array 0, 1. Write-Host always prints, and it can't be silenced or captured.

function Get-ErrorCount {
    param([string]$Path)
    $errorLines = [System.Collections.Generic.List[string]]::new()
    foreach ($line in Get-Content -Path $Path) {
        if ($line -match ' ERROR ') { $errorLines.Add($line) }
    }
    Write-Verbose "Scanned $Path"
    $errorLines.Count
}
 
$count = Get-ErrorCount -Path ./logs/auth.log
"count = $count"
count = 1

List[string].Add() returns nothing. Strictly speaking, -Verbose only reaches Write-Verbose once you also add [CmdletBinding()]. Add it and Get-ErrorCount -Path ./logs/auth.log -Verbose shows the message.

Exercise 3: A validated log-line buildermedium

Write New-LogLine with a mandatory -Message, a -Level limited to INFO, WARN or ERROR (default INFO), a -Service name that must be lowercase letters, digits and hyphens starting with a letter (default app), and a -Utc switch. It should return a line like 2026-11-09T21:47:04 WARN worker disk 91% full, with the level always upper-case. Show that -Level DEBUG and -Service 'Billing API' are rejected.

Show Solution
function New-LogLine {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Message,
 
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level = 'INFO',
 
        [ValidatePattern('^[a-z][a-z0-9-]*$')]
        [string]$Service = 'app',
 
        [switch]$Utc
    )
    $now = if ($Utc) { [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') } else { (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss') }
    '{0} {1} {2} {3}' -f $now, $Level.ToUpper(), $Service, $Message
}
 
New-LogLine -Message 'cache warmed' -Service api -Utc
New-LogLine -Message 'disk 91% full' -Level warn -Service worker
New-LogLine -Message 'x' -Level DEBUG
New-LogLine -Message 'x' -Service 'Billing API'
2026-11-10T02:46:59Z INFO api cache warmed
2026-11-09T21:47:04 WARN worker disk 91% full
New-LogLine: /home/sid/functions/ex3.ps1:21
Line |
  21 |  New-LogLine -Message 'x' -Level DEBUG
     |                                  ~~~~~
     | Cannot validate argument on parameter 'Level'. The argument "DEBUG" does
     | not belong to the set "INFO,WARN,ERROR" specified by the ValidateSet
     | attribute. Supply an argument that is in the set and then try the
     | command again.
New-LogLine: /home/sid/functions/ex3.ps1:22
Line |
  22 |  New-LogLine -Message 'x' -Service 'Billing API'
     |                                    ~~~~~~~~~~~~~
     | Cannot validate argument on parameter 'Service'. The argument "Billing
     | API" does not match the "^[a-z][a-z0-9-]*$" pattern. Supply an argument
     | that matches "^[a-z][a-z0-9-]*$" and try the command again.

-Level warn was accepted because ValidateSet ignores case, which is why the function calls .ToUpper(). The UTC line shows the next day's date because the test machine's local time zone is several hours behind UTC.

Exercise 4: Rename files safely from the pipelinehard

Write Add-DatePrefix, which takes files from Get-ChildItem through the pipeline (bind -Path from the FullName property) and renames each one to yyyy-MM-dd_<original name>, using the file's LastWriteTime. It must support -WhatIf, skip files that already have a date prefix (and say so under -Verbose), and report how many files it renamed in the end block. Running it twice must not double-prefix anything.

Show Solution
function Add-DatePrefix {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias('FullName')]
        [string]$Path
    )
    begin {
        $renamed = 0
    }
    process {
        $item = Get-Item -LiteralPath $Path
        $newName = '{0:yyyy-MM-dd}_{1}' -f $item.LastWriteTime, $item.Name
        if ($item.Name -match '^\d{4}-\d{2}-\d{2}_') {
            Write-Verbose "Skipping $($item.Name): already prefixed"
            return
        }
        if ($PSCmdlet.ShouldProcess($item.Name, "Rename to $newName")) {
            Rename-Item -LiteralPath $item.FullName -NewName $newName
            $renamed++
        }
    }
    end {
        Write-Verbose "$renamed file(s) renamed"
    }
}
 
New-Item -ItemType Directory -Path ./scans -Force | Out-Null
'invoice.pdf', 'receipt.pdf' | ForEach-Object {
    $f = New-Item -ItemType File -Path "./scans/$_" -Force
    $f.LastWriteTime = [datetime]'2026-10-31 09:15'
}
 
Get-ChildItem -Path ./scans -File | Add-DatePrefix -WhatIf
Get-ChildItem -Path ./scans -File | Add-DatePrefix -Verbose
Get-ChildItem -Path ./scans -File | Add-DatePrefix -Verbose
(Get-ChildItem -Path ./scans).Name
What if: Performing the operation "Rename to 2026-10-31_invoice.pdf" on target "invoice.pdf".
What if: Performing the operation "Rename to 2026-10-31_receipt.pdf" on target "receipt.pdf".
VERBOSE: Performing the operation "Rename to 2026-10-31_invoice.pdf" on target "invoice.pdf".
VERBOSE: Performing the operation "Rename to 2026-10-31_receipt.pdf" on target "receipt.pdf".
VERBOSE: 2 file(s) renamed
VERBOSE: Skipping 2026-10-31_invoice.pdf: already prefixed
VERBOSE: Skipping 2026-10-31_receipt.pdf: already prefixed
VERBOSE: 0 file(s) renamed
2026-10-31_invoice.pdf
2026-10-31_receipt.pdf

return inside process skips to the next pipeline object (like continue in a loop). The second real run proves the function is idempotent, which is what makes it safe to schedule.


Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 on Windows 11, November 2026. Every function and call was run as shown with pwsh -NoProfile -File. For the prompt examples, answers were piped to standard input, and the failure cases were run with -NonInteractive. On 5.1 I re-ran the unrolling, common-parameter, ErrorMessage and ValidateSet examples. The surprise was that Write-Output -NoEnumerate does nothing on 5.1. I also confirmed that a misspelled help keyword, or two blank lines above function, really does disable comment-based help. Paths from the test machine's scratch directories are shown shortened to /home/sid/….

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.