Ref: AI Tools/ChatGPT
[CmdletBinding()] turns a normal PowerShell function into an advanced function.
That means the function behaves more like a real PowerShell cmdlet.
Basic example
Normal function:
function Install-Office {
param(
[string]$Version
)
Write-Host "Installing Office $Version"
}
Advanced function:
function Install-Office {
[CmdletBinding()]
param(
[string]$Version
)
Write-Host "Installing Office $Version"
}
What [CmdletBinding()] does
It gives your function cmdlet-style behavior, such as:
| Feature | Meaning |
|---|---|
| Common parameters | Allows parameters like -Verbose, -Debug, -ErrorAction |
| Better parameter handling | Works better with [Parameter()], mandatory parameters, parameter sets |
| Pipeline support | Works well with ValueFromPipeline and process {} |
| Professional structure | Makes custom functions look and behave more like built-in cmdlets |
Example with -Verbose
function Test-LabFunction {
[CmdletBinding()]
param(
[string]$Name
)
Write-Verbose "The function received the name $Name"
Write-Host "Hello $Name"
}
Run normally:
Test-LabFunction -Name "Sayed"
Output:
Hello Sayed
Run with -Verbose:
Test-LabFunction -Name "Sayed" -Verbose
Output:
VERBOSE: The function received the name Sayed
Hello Sayed
Without [CmdletBinding()], -Verbose would not work the same way.
Example with mandatory parameter
function Install-Office {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet("2013","2016")]
[string]$Version
)
Write-Host "I installed Office $Version."
}
Now if the user runs:
Install-Office
PowerShell asks for the missing mandatory value:
cmdlet Install-Office at command pipeline position 1
Supply values for the following parameters:
Version:
Simple explanation for students
[CmdletBinding()]upgrades a function into an advanced PowerShell function. It allows the function to support cmdlet-like features such as-Verbose, better parameter behavior, validation, parameter sets, and pipeline-friendly design.
Very short version
[CmdletBinding()]
means:
“Treat this function like a professional PowerShell cmdlet.”
