Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 34 ยท Functions and Scripts

Advanced Functions

Turn PowerShell functions into cmdlet-like tools with CmdletBinding, mandatory and validated parameters, pipeline input, begin/process/end and -WhatIf.

A basic function takes arguments and prints a result. An advanced function behaves like a compiled cmdlet: it can require parameters, check their values, accept objects from the pipeline, support -Verbose and -ErrorAction, and even promise not to change anything when the caller passes -WhatIf. You get all of this by adding a few attributes to the function you already know from Functions and Parameters.

The PowerShell in this lesson is read-only, because the site has no PowerShell host. The runnable examples are JavaScript stand-ins that model validation, the pipeline phases and the -WhatIf check. Each says clearly that it is a model.

CmdletBinding

Put [CmdletBinding()] above the param block. That one attribute turns the function into an advanced function and adds the common parameters: -Verbose, -Debug, -ErrorAction, -WarningAction, -InformationAction, -ErrorVariable, -WarningVariable, -InformationVariable, -OutVariable, -OutBuffer and -PipelineVariable. Recent versions of PowerShell 7 add -ProgressAction too. None of them need any code from you.

POWERSHELL
function Get-Square {
    [CmdletBinding()]
    param(
        [int]$Number
    )
    Write-Verbose "Squaring $Number"
    $Number * $Number
}

Get-Square -Number 6              # 36
Get-Square -Number 6 -Verbose     # shows VERBOSE: Squaring 6, then 36

Write-Verbose prints only when the caller asks with -Verbose, so you can leave helpful diagnostics in the code at no cost to normal runs. Advanced functions also reject unknown parameters and extra positional arguments, where a basic function would silently ignore them in $args.

Parameter attributes

The [Parameter()] attribute describes how one parameter is supplied. Validation attributes check the value before your code runs, so the error message mentions the parameter and the rule.

POWERSHELL
function Set-Volume {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('Music', 'Video', 'Alerts')]
        [string]$Channel,

        [ValidateRange(0, 100)]
        [int]$Level = 50,

        [ValidateNotNullOrEmpty()]
        [string]$Reason = 'user request'
    )
    "Channel $Channel set to $Level ($Reason)"
}

Set-Volume -Channel Music -Level 80
Set-Volume -Channel Podcast         # error: 'Podcast' is not in the set
Set-Volume                          # prompts for the mandatory Channel

The most useful attributes:

Attribute What it enforces
Mandatory The caller must supply it; PowerShell prompts if they do not
ValidateSet('a','b') The value must be one of the listed ones, and tab completion lists them
ValidateRange(min, max) A number must be inside the range
ValidatePattern('regex') A string must match the regular expression
ValidateLength(min, max) A string must have a length within the range
ValidateNotNullOrEmpty() Rejects $null and empty strings or arrays
ValidateScript({ ... }) Your own test; return true to accept

Prefer these attributes over if checks at the top of the function. The errors are consistent, the help system documents them and the code stays short.

Basic versus advanced

Basic function Takes arguments, ignores extras, no common parameters.
Advanced function [CmdletBinding()] adds -Verbose, -ErrorAction and more.

One attribute changes how the whole function behaves.

1 / 2

The stand-in below checks arguments against a spec in the same order PowerShell does: missing mandatory values first, then conversion and validation. It is a model, not the real binder.

JS A parameter validation model

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pipeline input and begin, process, end

A function becomes a good pipeline citizen when it accepts input from the pipeline. Mark a parameter with ValueFromPipeline to receive whole objects, or ValueFromPipelineByPropertyName to match a property with the same name. Then split the body into three blocks.

POWERSHELL
function Get-FileSizeKB {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [string]$FullName
    )
    begin {
        $total = 0
        Write-Verbose 'Starting'
    }
    process {
        $kb = [math]::Round((Get-Item -LiteralPath $FullName).Length / 1KB, 1)
        $total += $kb
        [pscustomobject]@{ Path = $FullName; SizeKB = $kb }
    }
    end {
        Write-Verbose "Total: $total KB"
    }
}

Get-ChildItem *.log | Get-FileSizeKB
  • begin runs once before the first item. Use it for setup.
  • process runs once for each pipeline object, with the current one in the parameter variable.
  • end runs once after the last item. Use it for totals and cleanup.

If you write a function body without these blocks, the whole body is treated as an end block. That means a pipeline-aware function without a process block sees only the last piece of input. Always add process when you accept pipeline input, and put per-item work inside it. This ties directly to how objects stream, as described in The Pipeline.

The model below runs a pipeline-aware function with JavaScript generators. Items flow through one at a time, and begin and end fire once. It is a stand-in for the real pipeline engine.

JS begin, process and end with generators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

-WhatIf and -Confirm

A function that changes things should let the caller rehearse. Add SupportsShouldProcess to CmdletBinding, and the function gains -WhatIf and -Confirm. You then guard every change with $PSCmdlet.ShouldProcess().

POWERSHELL
function Remove-OldLog {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [string]$FullName
    )
    process {
        if ($PSCmdlet.ShouldProcess($FullName, 'Delete log file')) {
            Remove-Item -LiteralPath $FullName
        }
    }
}

Get-ChildItem *.log | Remove-OldLog -WhatIf
# What if: Performing the operation "Delete log file" on target "C:\logs\app.log".

ShouldProcess(target, action) returns $true when the work should happen. With -WhatIf it prints the message and returns $false, so the Remove-Item call is skipped. With -Confirm it asks the user first. ConfirmImpact (Low, Medium or High) sets how risky the function is: when its level is at or above the session's $ConfirmPreference (High by default), PowerShell asks for confirmation even without -Confirm.

The rule is simple: wrap each destructive action in ShouldProcess, so that -WhatIf really prevents every change the function would make.

This model shows the decision logic as a function. It mirrors the rules above and is not the real engine.

JS A -WhatIf and -Confirm decision model

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run Get-Help about_Functions_Advanced_Parameters in a real session for the full attribute list, as shown in Getting Help.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does adding [CmdletBinding()] above a function's param block give you?

    CmdletBinding makes the function advanced. You gain the common parameters, and unknown or extra arguments are rejected instead of landing in $args.
  2. 2. A function accepts pipeline input but has no begin, process or end block. Which input does it see?

    Without named blocks, the whole body is an end block, which runs after the pipeline finishes. Put per-item work in process.
  3. 3. Which attribute makes PowerShell ask for a value when the caller leaves a parameter out?

    Parameter(Mandatory) makes the parameter required and prompts for it when missing. The others check or position values.
  4. 4. What does ShouldProcess return when the caller used -WhatIf?

    With -WhatIf, ShouldProcess prints what would happen and returns $false so the guarded code is skipped.
  5. 5. Where should a total be written out after all pipeline items have been counted?

    end runs once after the last item, which is the place for totals and cleanup.

Summary

  • [CmdletBinding()] makes an advanced function with the common parameters and stricter binding.
  • [Parameter(Mandatory)] and the Validate* attributes check input before your code runs.
  • ValueFromPipeline and ValueFromPipelineByPropertyName let a function accept pipeline input, which needs a process block.
  • begin runs once first, process once per item, end once last.
  • SupportsShouldProcess plus $PSCmdlet.ShouldProcess() adds -WhatIf and -Confirm.

Next, store functions in files and learn how PowerShell decides whether to run them in Scripts and Execution Policy.