PowerShell/02core11 min

Parameters, validation and [CmdletBinding()]

The ZEUS probe scripts accept parameters — the forest to scan, the -AsJson mode, credentials. Well-defined, validated parameters are the difference between a solid tool and a fragile script. The key is [CmdletBinding()].

The param block and typing

We declare parameters in the param() block, always with a type.

function Get-LsnInventory {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Forest,

        [int]$PageSize = 1000,

        [switch]$AsJson
    )
    # ...
}

ProfessNet standard: every probe function has [CmdletBinding()], every parameter has an explicit type. Machine mode is enabled by [switch]$AsJson — by default the output is for a human, with the flag — JSON on stdout.

What [CmdletBinding()] gives you

This one line turns an ordinary function into an advanced function: you get -Verbose, -Debug, -ErrorAction and the automatic $PSCmdlet variable for free.

function Get-LsnForest {
    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$Forest)

    Write-Verbose "Connecting to forest $Forest"   # visible only with -Verbose
    # ...
}

Get-LsnForest -Forest corp.local -Verbose

Validation attributes

Instead of manual ifs we validate parameters declaratively. Invalid input is rejected before the function runs.

param(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$Forest,

    [ValidateRange(1, 5000)]
    [int]$PageSize = 1000,

    [ValidateSet("Forest", "Inventory", "Perf")]
    [string]$Mode = "Inventory",

    [ValidatePattern('^[a-z0-9.\-]+$')]
    [string]$Domain
)
AttributeChecks
[ValidateNotNullOrEmpty()]the value is non-empty
[ValidateRange(min,max)]a number within a range
[ValidateSet(...)]one of the allowed values
[ValidatePattern(regex)]a match against a pattern
[ValidateScript({...})]any logical condition

ProfessNet standard: we validate declaratively with attributes, not with ifs in the function body. That's shorter code and better error messages for the caller.

Pipeline parameters

We mark functions that accept data from the pipeline with ValueFromPipeline and process it in the process block.

function Test-LsnHost {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string]$ComputerName
    )
    process {
        [pscustomobject]@{
            Host    = $ComputerName
            Online  = Test-Connection $ComputerName -Count 1 -Quiet
        }
    }
}

"dc01", "dc02" | Test-LsnHost

Tip: the three blocks of an advanced function are begin (setup once), process (for each pipeline element) and end (cleanup). Put the logic for a single element in process.


[CmdletBinding()] plus typed, validated parameters turn a script into a real tool with -Verbose, automatic validation and pipeline support. This is the standard skeleton of every probe function in ZEUS.