11 Getting started with advanced functions

 

We’re almost there, we promise, but before we can start writing our own advanced functions, we’ll focus entirely on the Param() block of the example function in this chapter and discuss some of the cool things you can do with it.

11.1 About CmdletBinding and common parameters

What’s the difference between a simple function and an advanced function? It may surprise you to know that it’s just a single line of code—the CmdletBinding() attribute. This attribute adds so much functionality—let’s take a look. 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
    )
}

Again, ask for help:

PS C:\> help test
NAME
    test
SYNTAX
    test [[-ComputerName] <string>]  [<CommonParameters>]
ALIASES
    None

11.1.1 Accepting pipeline input

11.1.2 Mandatory-ness

11.1.3 Parameter validation

11.1.4 Parameter aliases

11.1.5 Supporting –Confirm and –WhatIf

11.2 Your turn