about_functions

TOPIC
    about_functions

SHORT DESCRIPTION
    Describes how to create and use Functions in Windows PowerShell.

LONG DESCRIPTION
    A Function is a list of statements that has a name that you assign. When
    you run a Function, you type the Function name. The statements in the list
    run as if you had typed them at the command prompt.

    Like cmdlets, Functions can have parameters. The parameters can be named,
    positional, switch, or dynamic parameters. Function parameters can be read
    from the command line or from the pipeline.

    Functions can return values that can be displayed, assigned to Variables,
    or passed to other Functions or cmdlets.

    The Function‘s statement list can contain different types of statement
    lists with the keywords Begin, Process, and End. These statement lists
    handle input from the pipeline differently.

    A filter is a special kind of Function that uses the Filter keyword.

    Functions can also act like cmdlets. You can create a Function that works
    just like a cmdlet without using C# programming. For more information,
    see about_functions_advanced.

Syntax
     The following is the syntax for a Function:

         Function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]
         {
             param([type]$parameter1 [,[type]$parameter2])

             dynamicparam {<statement list>}

             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     A Function includes the following items:

         – A Function keyword
         – A scope (optional)
         – A name that you select
         – Any number of named parameters (optional)
         – One or more Windows PowerShell commands enclosed in braces ({})

     For more information about the Dynamicparam keyword and dynamic
     parameters in Functions, see about_functions_advanced_parameters.

Simple Functions
     Functions do not have to be complicated to be useful. The following
     Function gets the Environment Variables that do not belong to the System
     account of the current system:

         Function other_env
         {
             Get-WmiObject win32_environment |
                where {$_.username -ne “<System>”}
         }

     To run the Function, type “other_env”.

     You can create a toolbox of useful small Functions. Add these Functions
     to your Windows PowerShell profile, as described in about_profiles and
     later in this topic.

Functions with Parameters
     You can use parameters with Functions, including named parameters,
     positional parameters, switch parameters, and dynamic parameters. For
     more information about dynamic parameters in Functions,
     see about_functions_advanced_parameters.

Named Parameters
     You can define any number of named parameters. You can include a default
     value for named parameters, as described later in this topic.

     You can define parameters inside the braces using the Param keyword, as
     shown in the following sample syntax:

         Function <name> {
             param ([type]$parameter1[,[type]$parameter2])
             <statement list>
         }

     You can also define parameters outside the braces without the Param
     keyword, as shown in the following sample syntax:

         Function <name> [([type]$parameter1[,[type]$parameter2])] {
             <statement list>
         }

     There is no difference between these two methods. Use the method that
     you prefer.

     When you run the Function, the value you supply for a parameter is
     assigned to a Variable that contains the parameter name. The value of
     that Variable can be used in the Function.

     The following example is a Function called Small_files. This Function
     has a $size parameter. The Function displays all the files that are
     smaller than the value of the $size parameter, and it excludes
     directories:

         Function small_files {
             param ($size)
             Get-ChildItem c:\ | where {
                 $_.length -lt $size -and !$_.PSIsContainer}
         }

     In the Function, you can use the $size Variable, which is the name
     defined for the parameter.

     To use this Function, type the following command:

         C:\PS> Function small_files –size 50

     You can also enter a value for a named parameter without the parameter
     name. For example, the following command gives the same result as a
     command that names the Size parameter:

         C:\PS> Function small_files 50

     To define a default value for a parameter, type an equal sign and the
     value after the parameter name, as shown in the following variation of
     the Small_files example:

         Function small_files ($size = 100) {
             Get-ChildItem c:\ | where {
                 $_.length -lt $size -and !$_.PSIsContainer}
         }

     If you type “small_files” without a value, the Function assigns 100 to
     $size. If you provide a value, the Function uses that value.

Positional Parameters
     A positional parameter is a parameter without a parameter name. Windows
     PowerShell uses the parameter value order to associate each parameter
     value with a parameter in the Function.

     When you use positional parameters, type one or more values after the
     Function name. Positional parameter values are assigned to the $args
     array Variable. The value that follows the Function name is assigned to
     the first position in the $args array, $args[0].

     The following Extension Function adds the .txt file name extension to a
     file name that you supply:

         Function extension {
             $name = $args[0] + “.txt”
             $name
         }

         C:\PS> extension myTextFile
         myTextFile.txt

     Functions can take more than one positional parameter. The following
     example displays any values entered with the Function name.

         Function repeat { foreach ($arg in $args) { “The input is $arg” } }

         C:\PS>repeat one
         The input is one

         C:\PS> repeat one two three
         The input is one
         The input is two
         The input is three

     This Function can be used with any number of values. The Function
     assigns each value to a position in the $args array.

Switch Parameters
     A switch is a parameter that does not require a value. Instead, you type
     the Function name followed by the name of the switch parameter.

     To define a switch parameter, specify the type [switch] before the
     parameter name, as shown in the following example:

         Function switchExample {
             param ([switch]$on)
             if ($on) { “Switch on” }
             else { “Switch off” }
         }

     When you type the On switch parameter after the Function name, the
     Function displays “Switch on”. Without the switch parameter, it displays
     “Switch off”.

         C:\PS> SwitchExample -on
         Switch on

         C:\PS> SwitchExample
         Switch off

     You can also assign a Boolean value to a switch when you run the
     Function, as shown in the following example:

         C:\PS> SwitchExample -on:$true
         Switch on

         C:\PS> SwitchExample -on:$false
         Switch off

Piping Objects to Functions
     Any Function can take input from the pipeline. You can control how a
     Function processes input from the pipeline using Begin, Process, and End
     keywords. The following sample syntax shows the three keywords:

         Function <name> {
             begin {<statement list>}
             process {<statement list>}
             end {<statement list>}
         }

     The Begin statement list runs one time only, at the beginning of
     the Function.

     The Process statement list runs one time for each object in the pipeline.
     While the Process block is running, each pipeline object is assigned to
     the $_ automatic Variable, one pipeline object at a time.

     After the Function receives all the objects in the pipeline, the End
     statement list runs one time. If no Begin, Process, or End keywords are
     used, all the statements are treated like an End statement list.

     The following Function uses the Process keyword. The Function displays
     examples from the pipeline:

         Function pipelineFunction
         {
             process {“The value is: $_”}
         }

     To demonstrate this Function, enter an array of numbers created with
     commas, as shown in the following example:

         C:\PS> 1,2,4 | pipelineFunction
         The value is: 1
         The value is: 2
         The value is: 4

     When you use a Function in a pipeline, the objects piped to the Function
     are assigned to the $input automatic Variable. The Function runs
     statements with the Begin keyword before any objects come from the
     pipeline. The Function runs statements with the End keyword after all
     the objects have been received from the pipeline.

     The following example shows the $input automatic Variable with Begin and
     End keywords.

         Function PipelineBeginEnd
         {
             begin {“Begin: The input is $input”}
             end {“End: The input is $input” }
         }

     If this Function is run by using the pipeline, it displays the following
     results:

         C:\PS> 1,2,4 | PipelineBeginEnd
         Begin: The input is
         End: The input is 1 2 4

     When the Begin statement runs, the Function does not have the input from
     the pipeline. The End statement runs after the Function has the values.

     If the Function has a Process keyword, the Function reads the data in
     $input. The following example has a Process statement list:

         Function PipelineInput
         {
             process {“Processing: $_ ” }
             end {“End: The input is: $input” }
         }

     In this example, each object that is piped to the Function is sent to the
     Process statement list. The Process statements run on each object, one
     object at a time. The $input automatic Variable is empty when the
     Function reaches the End keyword.

         C:\PS> 1,2,4 | PipelineInput
         Processing: 1
         Processing: 2
         Processing: 4
         End: The input is:

Filters
     A filter is a type of Function that runs on each object in the pipeline.
     A filter resembles a Function with all its statements in a Process block.

     The syntax of a filter is as follows:

         filter [<scope:>]<name> {<statement list>}

     The following filter takes log entries from the pipeline and then
     displays either the whole entry or only the message portion of the entry:

         filter ErrorLog ([switch]$message)
         {
             if ($message) { Out-Host -inputobject $_.Message }
             else { $_ }
         }

Function Scope
     A Function exists in the scope in which it was created.

     If a Function is part of a script, the Function is available to
     statements within that script. By default, a Function in a script is not
     available at the command prompt.

     You can specify the scope of a Function. For example, the Function is
     added to the global scope in the following example:

         Function global:get-dependentsvs { Get-Service |
             where {$_.dependentservices} }

     When a Function is in the global scope, you can use the Function in
     scripts, in Functions, and at the command line.

     Functions normally create a scope. The items created in a Function, such
     as Variables, exist only in the Function scope.

     For more information about scope in Windows PowerShell, see about_Scopes/”>about_Scope.

Finding and Managing Functions Using the Function: Drive
     All the Functions and filters in Windows PowerShell are automatically
     stored in the Function: drive. This drive is exposed by the Windows
     PowerShell Function provider.

     When referring to the Function: drive, type a colon after Function, just
     as you would do when referencing the C or D drive of a computer.

     The following command displays all the Functions in the current session
     of Windows PowerShell:

         C:\PS>    dir Function:

     The commands in the Function are stored as a script block in the
     definition property of the Function. For example, to display the
     commands in the Help Function that comes with Windows PowerShell, type:

         (dir Function:help).definition

     For more information about the Function: drive, see Function.

Reusing Functions in New Sessions
     When you type a Function at the Windows PowerShell command prompt, the
     Function becomes part of the current session. It is available until the
     session ends.

     To use your Function in all Windows PowerShell sessions, add the Function
     to your Windows PowerShell profile. For more information about profiles,
     see about_profiles.

     You can also save your Function in a Windows PowerShell script file.
     Type your Function in a text file, and then save the file with the .ps1
     file name extension.

Writing Help for Functions
    The Get-Help cmdlet gets help for Functions, as well as for cmdlets,
    providers, and scripts. To get help for a Function, type Get-Help followed
    by the Function name.

    For example, to get help for the MyDisks Function, type:

        Get-Help MyDisks

    You can write help for a Function by using either of the two following methods:

    — Comment-Based Help for Functions

        Create a help topic by using special keywords in the comments. To create
        comment-based help for a Function, the comments must be placed at the
        beginning or end of the Function body or on the lines preceding the Function
        keyword. For more information about comment-based help, see
        about_Comment_Based_Help.

    — XML-Based Help for Functions

        Create an XML-based help topic, such as the type that is typically
        created for cmdlets. XML-based help is required if you are localizing
        help topics into multiple languages.

        To associate the Function with the XML-based help topic, use the
        .ExternalHelp help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see “How to Write Cmdlet Help” in MSDN.

SEE ALSO
    about_Automatic_Variables
    about_Comment_Based_Help
    about_functions_advanced
    about_functions_CmdletBindingAttribute
    about_parameters
    about_profiles
    about_scopes
    about_script_blocks
    Function (provider)