PowerShell Cmdlet Binding
Cmdlet binding is the [CmdletBinding()] marker that turns a plain function into an advanced function. An advanced function behaves more like a built-in command than a plain function.
Verbose stays silent by default
Without any switch, the verbose line prints nothing and only the result appears.
function Show-Progress {
[CmdletBinding()]
param([string]$Name)
Write-Verbose "Working on $Name"
"Done for $Name"
}
Show-Progress -Name "Ana"The -Verbose switch turns it on
Calling the same function with -Verbose shows the progress line above the result.
function Show-Progress {
[CmdletBinding()]
param([string]$Name)
Write-Verbose "Working on $Name"
"Done for $Name"
}
Show-Progress -Name "Ana" -Verbose$PSCmdlet names the running command
Inside an advanced function, $PSCmdlet describes the command that is running.
function Show-Progress {
[CmdletBinding()]
param([string]$Name)
"Running: " + $PSCmdlet.MyInvocation.MyCommand.Name
}
Show-Progress -Name "Ana"Example
function Copy-Report {
[CmdletBinding()]
param([string]$Name)
Write-Verbose "Starting $Name"
Write-Verbose "Finishing $Name"
"Copied $Name"
}
$VerbosePreference = "Continue"
Copy-Report -Name "report.txt"Key points
- [CmdletBinding()]: a marker placed above param that turns a plain function into an advanced function.
- Use [CmdletBinding()] when a function should act like a built-in command.
- Write-Verbose: a command that prints an extra progress message, but only when verbose output is turned on.
- Verbose output stays silent by default, so normal runs stay clean.
- $PSCmdlet: an automatic variable inside an advanced function that describes the running command.
In this example, an advanced function prints two verbose lines around its result. Setting $VerbosePreference to Continue turns verbose output on for the whole script, so both lines appear before the result.
Note
A verbose message prints with a VERBOSE: label in front of it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How do you see the Write-Verbose message from an advanced function?