PowerShell


PowerShell Functions All Versions

1.0
2.0
3.0
4.0
5.0
5.1 Preview

This draft deletes the entire topic.

Introduction

A function is basically a named block of code. When you call the function name, the script block within that function runs. It is a list of PowerShell statements that has a name that you assign. When you run a function, you type the function name.It is a method of saving time when tackling repetitive tasks. PowerShell formats in three parts: the keyword 'Function', followed by a Name, finally, the payload containing the script block, which is enclosed by curly/parenthesis style bracket.

expand all collapse all

Examples

  • Improvements requested:

    • This example does not sufficiently illustrate the point and needs to be edited to provide more details. –  TravisEz13 Dec 2 at 23:11
      Advanced Functions should be used over functions, this topic does not make this clear.
    7

    A function can be defined with parameters using the param block:

    function Get-Greeting {
        param
        (
            $name,
            $age
        )
        "Hello $name, age $age"
    }
    

    Or using the simple function syntax (more C# style syntax):

    function Get-Greeting($name, $age) {
        "Hello $name, age $age"
    }
    

    Note: This format is as good as the advanced format, but has very limited capabilities.
    Try using a parameter set, parameter validation, ...
    Because of this and because I like uniformity I prefer to use the advanced format for every function.

    This function can then be invoked with ordered parameters where the order of the parameters on the invocation is matched to the order of the declaration in the function header

    $greeting = Get-Greeting "Jim" 82
    

    Alternatively, this function can be invoked with named parameters

    $greeting = Get-Greeting -name "Bob" -age 82
    

    Note: PowerShell functions are never called with the syntax Get-Greeting("Jim", 82), doing this will pass one array in as the first parameter and leave the second parameter empty.

  • 6
    <#
    .Synopsis
       Short description
    .DESCRIPTION
       Long description
    .EXAMPLE
       Example of how to use this cmdlet
    .EXAMPLE
       Another example of how to use this cmdlet
    .INPUTS
       Inputs to this cmdlet (if any)
    .OUTPUTS
       Output from this cmdlet (if any)
    .NOTES
       General notes
    .COMPONENT
       The component this cmdlet belongs to
    .ROLE
       The role this cmdlet belongs to
    .FUNCTIONALITY
       The functionality that best describes this cmdlet
    #>
    function Verb-Noun
    {
        [CmdletBinding(DefaultParameterSetName='Parameter Set 1', 
                      SupportsShouldProcess=$true, 
                      PositionalBinding=$false,
                      HelpUri = 'http://www.microsoft.com/',
                      ConfirmImpact='Medium')]
        [Alias()]
        [OutputType([String])]
        Param
        (
            # Param1 help description
            [Parameter(Mandatory=$true, 
                       ValueFromPipeline=$true,
                       ValueFromPipelineByPropertyName=$true, 
                       ValueFromRemainingArguments=$false, 
                       Position=0,
                       ParameterSetName='Parameter Set 1')]
            [ValidateNotNull()]
            [ValidateNotNullOrEmpty()]
            [ValidateCount(0,5)]
            [ValidateSet("sun", "moon", "earth")]
            [Alias("p1")] 
            $Param1,
    
            # Param2 help description
            [Parameter(ParameterSetName='Parameter Set 1')]
            [AllowNull()]
            [AllowEmptyCollection()]
            [AllowEmptyString()]
            [ValidateScript({$true})]
            [ValidateRange(0,5)]
            [int]
            $Param2,
    
            # Param3 help description
            [Parameter(ParameterSetName='Another Parameter Set')]
            [ValidatePattern("[a-z]*")]
            [ValidateLength(0,15)]
            [String]
            $Param3
        )
    
        Begin
        {
        }
        Process
        {
            if ($pscmdlet.ShouldProcess("Target", "Operation"))
            {
            }
        }
        End
        {
        }
    }
    
  • 4

    Parameters to a function can be marked as mandatory

    function Get-Greeting{
        param
        (
            [Parameter(Mandatory=$true)]$name
        )
        "Hello World $name"
    }
    

    If the function is invoked without a value, the command line will prompt for the value:

    $greeting = Get-Greeting 
    
    cmdlet Get-Greeting at command pipeline position 1
    Supply values for the following parameters:
    name: 
    
Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about PowerShell Functions? Ask Question

Topic Outline