Functions Like Cmdlets
Functions with verb-noun names, parameters that check themselves, pipeline input, -WhatIf in your own tools, and help that Get-Help reads.
Updated
Functions
- Functions: Naming a Job (Journeyman): A function you share gets a cmdlet's kind of name, an approved verb from Get-Verb and a singular noun, takes its inputs in param() and outputs objects rather than sentences, so its results can be sorted, filtered and saved; a file of functions is loaded into your session with a dot.
- Advanced Functions: `[CmdletBinding()]` (Journeyman): One line, [CmdletBinding()] above param(), turns a function into an advanced function that binds its parameters the way a cmdlet does: it refuses a misspelled parameter instead of quietly ignoring it, and gets -Verbose, -ErrorAction and the other common parameters for free.
- Checking Input: Validation Attributes (Journeyman): Validation attributes check a parameter's value before any line of the function runs: [ValidateSet()] allows only a list of choices and makes Tab fill them in, [ValidateRange()] keeps a number between two limits, [ValidateNotNullOrEmpty()] turns away an empty value, and Mandatory asks for one that's missing.
- Taking Pipeline Input (Freelancer): A parameter marked [Parameter(ValueFromPipeline)] receives each object that comes down the pipeline, a process block runs once for each of them, and begin and end run once before the first and after the last, for the setup and the totals.
Safety and Help
- `-WhatIf` in Your Own Tools (Freelancer): SupportsShouldProcess in [CmdletBinding()] gives a function -WhatIf and -Confirm, and wrapping each change in if ($PSCmdlet.ShouldProcess(target, action)) makes it print a What if: line instead of changing anything, or ask before each change, exactly like Remove-Item.
- Help for Your Tool (Journeyman): A comment block at the top of a function, with keywords such as .SYNOPSIS, .DESCRIPTION, .PARAMETER and .EXAMPLE, becomes the function's help page, so Get-Help, -Examples and -Parameter explain your tool the way they explain PowerShell's own commands.
Exercise: The Playlist Tools
- Exercise: The Playlist Tools (Journeyman): Turn four rough functions for a homework playlist into tools that behave like PowerShell's own commands, with verb-noun names, objects for output, checked input, pipeline input, -WhatIf and help, while a Pester check tries each one on its own copy of the playlist.