Chapter 11. Going advanced with your function

 

In this chapter, we’ll focus entirely on the Param() block of the example function and discuss some of the cool things you can do with it.

11.1. About CmdletBinding and common parameters

Back when PowerShell v2 was being developed, Microsoft toyed with the idea of having a cmdlet{} construct that was essentially a superset of function{}. The idea was that these “script cmdlets” would exhibit all the behaviors of a “real” cmdlet (for example, one written in .NET and compiled into an assembly). By the time v2 released, these had become advanced functions, and they’re differentiated primarily by the [CmdletBinding()] attribute. To illustrate the first major difference, let’s start with a basic function:

function test {
    Param(
    [string]$ComputerName
    )
}

That’s it. No code at all. Now ask PowerShell for help with that function:

PS C:\> help test

NAME
    test

SYNTAX
    test [[-ComputerName] <string>]

ALIASES
    None

That’s what we’d expect—PowerShell is producing the best help it can, given the complete nonexistence of anything. Now, let’s make one change to the code:

function test {
    [CmdletBinding()]
    Param(
        [string]$ComputerName
    )
}

and again ask for help:

PS C:\> help test

NAME
    test

SYNTAX
    test [[-ComputerName] <string>]  [<CommonParameters>]

ALIASES
    None

11.2. Your turn