PowerShell


PowerShell Functions All Versions

1.0
2.0
3.0
4.0
5.0
5.1 Preview

This draft deletes the entire topic.

expand all collapse all

Examples

  • 4

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

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

    Or using a more C# style syntax:

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

    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
    

    NB. 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.

  • 2
    <#
    .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
        {
        }
    }
    
  • 2

    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: 
    

I am downvoting this example because it is...

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about PowerShell Functions? Ask Question

Functions with parameters

4

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

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

Or using a more C# style syntax:

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

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

NB. 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.

Advanced Function

2
<#
.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
    {
    }
}

Mandatory Parameters

2

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: 

Simple Function with No Parameters

0

This is an example of a function which returns a string. In the example, the function is called in a statement assigning a value to a variable. The value in this case is the return value of the function.

function Get-Greeting{
    "Hello World"
}

# Invoking the function
$greeting = Get-Greeting

# demonstrate output
$greeting
Get-Greeting

function declares the following code to be a function.

Get-Greeting is the name of the function. Any time that function needs to be used in the script, the function can be called by means of invoking it by name.

{ ... } is the script block that is executed by the function.

If the above code is executed in the ISE, the results would be something like:

Hello World
Hello World

Topic Outline