PowerShell Advanced Functions
Add [CmdletBinding()] above a function's param() block and it becomes an advanced function: it behaves exactly like a compiled cmdlet. You get the common parameters (-Verbose, -ErrorAction, -WhatIf…), mandatory parameters, built-in validation and much more, with only a few attributes.
CmdletBinding and common parameters
function Get-Square {
[CmdletBinding()]
param([int]$Number)
Write-Verbose "Squaring $Number"
$Number * $Number
}
Get-Square -Number 7
Get-Square -Number 7 -Verbose
(Get-Command Get-Square).Parameters.Keys -contains 'ErrorAction'49
VERBOSE: Squaring 7
49
True
Parameter attributes
The [Parameter()] attribute controls how each parameter is bound:
| Setting | Meaning |
|---|---|
Mandatory |
the caller must supply a value |
Position = 0 |
may be given without its name, in this position |
ValueFromPipeline |
accepts whole objects from the pipeline |
ValueFromPipelineByPropertyName |
takes the value from a property with the same name |
HelpMessage = '…' |
hint shown when PowerShell prompts for a mandatory value |
ParameterSetName = 'ById' |
groups parameters into alternative "ways to call" |
function New-Account {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)]
[string]$UserName,
[Parameter(Position = 1)]
[string]$Department = 'General'
)
"Created $UserName in $Department"
}
New-Account ada Research
New-Account -UserName linusCreated ada in Research
Created linus in General
If a mandatory parameter is missing in an interactive session, PowerShell prompts for it. In a non-interactive script (like the ones verifying this site) it fails with an error instead.
Validation attributes
Validation attributes check arguments before your code runs and produce clear error messages, so you don't have to write the checks yourself:
| Attribute | Checks |
|---|---|
[ValidateNotNullOrEmpty()] |
not $null or '' |
[ValidateRange(1, 100)] |
number within a range |
[ValidateSet('Low', 'High')] |
one of the listed values (also gives tab completion) |
[ValidatePattern('^\d{4}#39;)] |
matches a regex |
[ValidateLength(3, 20)] |
string length |
[ValidateCount(1, 5)] |
number of array items |
[ValidateScript({ Test-Path $_ })] |
any custom test |
function Set-Priority {
[CmdletBinding()]
param(
[ValidateSet('Low', 'Normal', 'High')]
[string]$Level = 'Normal',
[ValidateRange(1, 10)]
[int]$Retries = 3
)
"Priority $Level with $Retries retries"
}
Set-Priority -Level High -Retries 5
try { Set-Priority -Level Urgent } catch { $_.Exception.Message }
try { Set-Priority -Retries 50 } catch { $_.Exception.Message }Priority High with 5 retries
Cannot validate argument on parameter 'Level'. The argument "Urgent" does not belong to the set "Low,Normal,High" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.
Cannot validate argument on parameter 'Retries'. The 50 argument is greater than the maximum allowed range of 10. Supply an argument that is less than or equal to 10 and then try the command again.
Supporting -WhatIf and -Confirm
Functions that change things should support -WhatIf and -Confirm. Declare SupportsShouldProcess and wrap the risky action in $PSCmdlet.ShouldProcess():
function Remove-OldLog {
[CmdletBinding(SupportsShouldProcess)]
param([string[]]$Name)
foreach ($file in $Name) {
if ($PSCmdlet.ShouldProcess($file, 'Delete log')) {
"Deleted $file"
}
}
}
Remove-OldLog -Name app.log, web.log -WhatIf
Remove-OldLog -Name app.logWhat if: Performing the operation "Delete log" on target "app.log".
What if: Performing the operation "Delete log" on target "web.log".
Deleted app.log
With -WhatIf, ShouldProcess prints a "What if" message and returns $false, so nothing is deleted. Without it, it returns $true and the action runs.
Parameter sets
Parameter sets let one function be called in different, mutually exclusive ways, like Get-Item -Path vs Get-Item -LiteralPath:
function Get-Order {
[CmdletBinding(DefaultParameterSetName = 'ById')]
param(
[Parameter(ParameterSetName = 'ById', Mandatory)]
[int]$Id,
[Parameter(ParameterSetName = 'ByCustomer', Mandatory)]
[string]$Customer
)
switch ($PSCmdlet.ParameterSetName) {
'ById' { "Looking up order #$Id" }
'ByCustomer' { "Listing orders of $Customer" }
}
}
Get-Order -Id 1042
Get-Order -Customer 'Contoso'
try { Get-Order -Id 1 -Customer 'x' } catch { 'Error: ' + $_.Exception.Message }Looking up order #1042
Listing orders of Contoso
Error: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
Comment-based help
Advanced functions deserve help. Put a comment block at the top of the function body; Get-Help then shows it like for any cmdlet:
function Set-Priority {
<#
.SYNOPSIS
Sets the priority of the current job.
.PARAMETER Level
Low, Normal or High.
.EXAMPLE
Set-Priority -Level High -Retries 5
#>
[CmdletBinding()]
param(...)
}Tip:
[OutputType([pscustomobject])]next to[CmdletBinding()]documents what the function returns, which editors use for IntelliSense.
Test yourself
What does adding [CmdletBinding()] to a function give you?
- Faster execution
- Common parameters like -Verbose and -ErrorAction, plus cmdlet behaviour
- Automatic logging
- It makes the function private
Which attribute restricts a parameter to the values 'Dev', 'Test' and 'Prod'?
- [ValidateRange('Dev','Prod')]
- [ValidateSet('Dev','Test','Prod')]
- [ValidatePattern('Dev|Test|Prod')] only
- [Allowed('Dev','Test','Prod')]
What does $PSCmdlet.ShouldProcess(...) return when the user passes -WhatIf?
- $true
- $false (after printing a What if message)
- An error
- The target name