PowerShell

Functions

A simple function looks like this:

function verb-noun {
            #Commands to run
        }
        

To make an advanced function all you need is a parameter block preceeded by an CmdletBinding block

        [CmdletBinding()]
        param(
    
        )
        

A classic example of an advanced function is:


        function Get-DiskSpaceInfo {
        <#
        .SYNOPSIS
        Retrieves basic disk capacity information from one 
        or more computers.
        .DESCRIPTION
        See the synopsis. This isn't complex. Note that
        this command uses WMI, not MIM, to connect to remote computers.
        it does not allow you to specify alternate credentials.
        .PARAMETER ComputerName
        One or more computer names or IP addresses, to query.
        For Example:
        Get-DiskSpaceInfo -Comptername One,Two,Three
        .PARAMETER LocalOny
        Specify this to include only local disks in the output.
        This is the default. To turn it off:
        Get-DiskSpcaceInfo -ComputerName Client -LocalOnly:$false
        .EXAMPLE
        Get-DiskSpaceInfo -Comptername One,Two
        .EXAMPLE
        Get-DiskSpaceInfo -Comptername 192.168.7.8
        #>
            [CmdletBinding()]
            param(
                [Parameter(Mandatory=$true,
                            Position=1,
                            HelpMessage='Computer to query')]
                [Alias('hostname')]        
                [string[]]$computername='w8p',
    
                [Parameter(Position=2)]
                [validateSet('Floppy','Local','Optical')]
                [string]$DriveType= 'Local'   
                )
            BEGIN{}
            PROCESS{
            foreach ($computer in $computername){
                $params = @{'Computername'=$computer;
                            'Class'='Win32_logicaldisk';
                        }
                switch ($DriveType){
                    'Local'{$params.add('Filter','DriveType=3'); break }
                    'Floppy'{$params.add('Filter','DriveType=2'); break }
                    'Optical'{$params.add('Filter','DriveType=5'); break }
                }
                Get-WmiObject @params |
                Select-Object @{n='Drive';e={$_.deviceID}},
                            @{n='Size';e={"{0:N2}" -f ($_.size / 1gb)}},                      
                            @{n='freescpace';e={"{0:N2}"  -f ($_.FreeSpace / 1gb) }},
                            @{n='freepercent';e={"{0:N2}"  -f ($_.FreeSpace / $_.size * 100) }},
                            PSComputername
                                
                        
            }
            }
            END{}
    
        }
    
        Get-DiskSpaceInfo localhost
    

Parameters

The main Parameter Attributes (Mandatory,Help Messages,Positional,Validation,Aliases)

The following comes from help about_functions_advanced_parameters

Mandatory


    Mandatory Argument
    
    The Mandatory argument indicates that the parameter is required. If this
    argument is not specified, the parameter is an optional parameter.
    
    The following example declares the ComputerName parameter. It uses the
    Mandatory argument to make the parameter mandatory.
    
    Param
      (
        [parameter(Mandatory=$true)]
        [String[]]
        $ComputerName
      )
    

Help Messages


        The HelpMessage argument specifies a string that contains a brief
        description of the parameter or its value. Windows PowerShell displays
        this message in the prompt that appears when a mandatory parameter value
        is missing from a command. This argument has no effect on optional parameters.
    
        The following example declares a mandatory ComputerName parameter and a
        help message that explains the expected parameter value.
    
    
        Param
            (
            [parameter(mandatory=$true,
                        HelpMessage="Enter one or more computer names separated by commas.")]
            [String[]]
            $ComputerName
            )
    

Positional


    The Position argument determines whether the parameter name is required
    when the parameter is used in a command. When a parameter declaration
    includes the Position argument, the parameter name can be omitted and
    Windows PowerShell identifies the unnamed parameter value by its position
    (or order) in the list of unnamed parameter values in the command.
    
    If the Position argument is not specified, the parameter name (or a parameter
    name alias or abbreviation) must precede the parameter value whenever the
    parameter is used in a command.
    
    By default, all function parameters are positional. Windows PowerShell
    assigns position numbers to parameters in the order in which the
    parameters are declared in the function. To disable this feature,
    set the value of the PositionalBinding argument of the CmdletBinding
    attribute to $False. The Position argument takes precedence over the
    value of the PositionalBinding argument for the parameters on which it
    is declared. For more information, see PositionalBinding in
    about_Functions_CmdletBindingAttribute.
    
    The value of the Position argument is specified as an integer. A position
    value of 0 represents the first position in the command, a position
    value of 1 represents the second position in the command, and so on.
    
    If a function has no positional parameters, Windows PowerShell assigns
    positions to each parameter based on the order in which the parameters
    are declared. However, as a best practice, do not rely on this assignment.
    When you want parameters to be positional, use the Position argument.
    
    The following example declares the ComputerName parameter. It uses the
    Position argument with a value of 0. As a result, when "-ComputerName"
    is omitted from command, its value must be the first or only unnamed
    parameter value in the command.
    
    Param
        (
        [parameter(Position=0)]
        [String[]]
        $ComputerName
        )
    
    
    NOTE: When the Get-Help cmdlet displays the corresponding "Position?" parameter
            attribute, the position value is incremented by 1. For example, a parameter
            with a Position argument value of 0 has a parameter attribute of
            "Position? 1."
    

Validation


    Parameter and Variable Validation Attributes
    
          Validation attributes direct Windows PowerShell to test the parameter
          values that users submit when they call the advanced function. If the parameter
          values fail the test, an error is generated and the function is not called. You
          can also use some of the validation attributes to restrict the values that users
          can specify for variables.
    
    
    
        AllowNull Validation Attribute
    
            The AllowNull attribute allows the value of a mandatory parameter
            to be null ($null). The following example declares a ComputerName parameter
            that can have a Null value.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [AllowNull()]
                [String]
                $ComputerName
              )
    
    
        AllowEmptyString Validation Attribute
    
            The AllowEmptyString attribute allows the value of a mandatory parameter to be
            an empty string (""). The following example declares a ComputerName parameter
            that can have an empty string value.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [AllowEmptyString()]
                [String]
                $ComputerName
              )
    
    
        AllowEmptyCollection Validation Attribute
    
            The AllowEmptyCollection attribute allows the value of a mandatory parameter
            to be an empty collection (@()). The following example declares a ComputerName
            parameter that can have a empty collection value.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [AllowEmptyCollection()]
                [String[]]
                $ComputerName
              )
    
    
        ValidateCount Validation Attribute
    
            The ValidateCount attribute specifies the minimum and maximum number
            of parameter values that a parameter accepts. Windows PowerShell
            generates an error if the number of parameter values in the command that
            calls the function is outside that range.
    
            The following parameter declaration creates a ComputerName parameter that
            takes 1 to 5 parameter values.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidateCount(1,5)]
                [String[]]
                $ComputerName
              )
    
    
        ValidateLength Validation Attribute
    
            The ValidateLength attribute specifies the minimum and maximum number
            of characters in a parameter or variable value. Windows PowerShell generates an
            error if the length of a value specified for a parameter or a variable
            is outside of the range.
    
            In the following example, each computer name must have one to 10
            characters.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidateLength(1,10)]
                [String[]]
                $ComputerName
              )
    
            In the following example, the value of the variable $number must be a
            minimum of one character in length, and a maximum of ten characters.
    
            [Int32][ValidateLength(1,10)]$number = 01
    
    
        ValidatePattern Validation Attribute
    
            The ValidatePattern attribute specifies a regular expression that
            is compared to the parameter or variable value. Windows PowerShell generates
            an error if the value does not match the regular expression
            pattern.
    
            In the following example, the parameter value must be a four-digit
            number, and each digit must be a number 0 to 9.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidatePattern("[0-9][0-9][0-9][0-9]")]
                [String[]]
                $ComputerName
              )
    
            In the following example, the value of the variable $number must be a
            four-digit number, and each digit must be a number 0 to 9.
    
            [Int32][ValidatePattern("[0-9][0-9][0-9][0-9]")]$number = 1111
    
        ValidateRange Validation Attribute
    
            The ValidateRange attribute specifies a numeric range for each
            parameter or variable value. Windows PowerShell generates an error
            if any value is outside that range. In the following example,
            the value of the Attempts parameter must be between 0 and 10.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidateRange(0,10)]
                [Int]
                $Attempts
              )
    
            In the following example, the value of the variable $number must be
            between 0 and 10.
    
            [Int32][ValidateRange(0,10)]$number = 5
    
    
        ValidateScript Validation Attribute
    
            The ValidateScript attribute specifies a script that is used
            to validate a parameter or variable value. Windows PowerShell
            pipes the value to the script, and generates an error if the
            script returns "false" or if the script throws an exception.
    
            When you use the ValidateScript attribute, the value
            that is being validated is mapped to the $_ variable. You can
            use the $_ variable to refer to the value in the script.
    
            In the following example, the value of the EventDate parameter
            must be greater than or equal to the current date.
    
            Param
              (
                [parameter()]
                [ValidateScript({$_ -ge (get-date)})]
                [DateTime]
                $EventDate
              )
    
    
           In the following example, the value of the variable $date must be
           greater than or equal to the current date and time.
    
           [DateTime][ValidateScript({$_ -ge (get-date)})]$date = (get-date)
    
        ValidateSet Attribute
    
            The ValidateSet attribute specifies a set of valid values for a
            parameter or variable. Windows PowerShell generates an error if a
            parameter or variable value does not match a value in the set. In
            the following example, the value of the Detail parameter can only
            be "Low," "Average," or "High."
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidateSet("Low", "Average", "High")]
                [String[]]
                $Detail
              )
    
            In the following example, the value of the variable $flavor must be
            either Chocolate, Strawberry, or Vanilla.
    
            [String][ValidateSet("Chocolate", "Strawberry", "Vanilla")]$flavor = Strawberry
    
    
    
        ValidateNotNull Validation Attribute
    
            The ValidateNotNull attribute specifies that the parameter
            value cannot be null ($null). Windows PowerShell generates an
            error if the parameter value is null.
    
            The ValidateNotNull attribute is designed to be used when the
            type of the parameter value is not specified or when the specified
            type will accept a value of Null. (If you specify a type that will
            not accept a null value, such as a string, the null value will be
            rejected without the ValidateNotNull attribute, because it does not
            match the specified type.)
    
            In the following example, the value of the ID parameter
            cannot be null.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidateNotNull()]
                $ID
              )
    
    
        ValidateNotNullOrEmpty Validation Attribute
    
            The ValidateNotNullOrEmpty attribute specifies that the parameter
            value cannot be null ($null) and cannot be an empty string ("").
            Windows PowerShell generates an error if the parameter is used in
            a function call, but its value is null, an empty string, or an empty
            array.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [ValidateNotNullOrEmpty()]
                [String[]]
                $UserName
              )
    
    

Aliases


    Alias Attribute
    
          The Alias attribute establishes an alternate name for the parameter. There
          is no limit to the number of aliases that you can assign to a parameter.
    
          The following example shows a parameter declaration that adds the "CN" and
          "MachineName" aliases to the mandatory ComputerName parameter.
    
            Param
              (
                [parameter(Mandatory=$true)]
                [alias("CN","MachineName")]
                [String[]]
                $ComputerName
              )