0
0
PowerShellscripting~7 mins

Advanced functions (CmdletBinding) in PowerShell

Choose your learning style9 modes available
Introduction
Advanced functions let you create powerful scripts that behave like built-in commands with extra features.
When you want your script to accept parameters with validation and help messages.
When you need to support common command features like -Verbose or -ErrorAction.
When you want to write reusable commands that integrate well with other PowerShell tools.
When you want to control how your function handles errors and output.
When you want to add detailed metadata to your function for better user experience.
Syntax
PowerShell
function FunctionName {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Param1
    )
    # Function code here
}
The [CmdletBinding()] attribute makes the function an advanced function.
Use param() block to define parameters with types and attributes.
Examples
A simple advanced function that requires a Name parameter and prints a greeting.
PowerShell
function Get-Greeting {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Name
    )
    Write-Output "Hello, $Name!"
}
An advanced function that supports the -Verbose switch to show extra messages.
PowerShell
function Test-Verbose {
    [CmdletBinding()]
    param()
    Write-Verbose "This is a verbose message."
    Write-Output "Done."
}
An advanced function with parameter validation and error handling.
PowerShell
function Get-Data {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [int]$Id
    )
    if ($Id -lt 0) {
        Write-Error "Id must be positive."
        return
    }
    Write-Output "Data for Id $Id"
}
Sample Program
This advanced function requires a Name and supports the common -Verbose switch. It shows a verbose message when -Verbose is used and then greets the user.
PowerShell
function Show-Info {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, HelpMessage="Enter your name.")]
        [string]$Name
    )

    Write-Verbose "Verbose mode is on."

    Write-Output "Hello, $Name!"
}

# Call the function with verbose
Show-Info -Name "Alice" -Verbose
OutputSuccess
Important Notes
Use [CmdletBinding()] to enable common parameters like -Verbose, -Debug, -ErrorAction.
Parameters can have attributes like Mandatory, HelpMessage, and Validate* to improve usability.
Write-Verbose messages only show if the user runs the function with -Verbose.
Summary
Advanced functions behave like real cmdlets with extra features.
Use [CmdletBinding()] and param() to define parameters and enable common switches.
They improve script usability, error handling, and integration with PowerShell.