Function

Using functions, you can combine all related processes into one.

Syntax

When using a function, you need to define it in advance.

# Function
function [<scope:>] Name (Parameters) {
    statement_block
}
 
# Filter
filter [<scope:>] Name (Parameters) {
    statement_block
}

When using a function that accepts parameters, avoid using parentheses.

return statement

As in other languages, return is supported.
However, the following two statements are equivalent, although the position of the return statement is different.

return $true
$true
return

exit statement

The exit statement can be used to return an error.

exit errorlevel

How to specify parameters

Automatic variable $args

The automatic variable $args stores parameters that have no parameter name specified.

function Double {
    foreach ($arg in $args) {
        $arg * 2
    }
}
PS> Double 2 3
4
6

Specify parameters

If you need parameters, write them in the form FunctionName ($item1, $item2) {}.

function Multiplication ($num) {
    Write-Host "num = $num, args = $args"
    foreach ($arg in $args) {
        $arg * $num
    }
}

To specify parameters, write FunctionName -item1 param1 -item2 param2.
If you specify the parameter names, you can change the order.
If the function requires parameters and does not have a parameter name, the first parameter will be assigned.

PS> Multiplication -num 2 2 3
num = 2, args = 2 3
4
6
PS> Multiplication 2 3 -num 5
num = 5, args = 2 3
10
15
PS> Multiplication 2 3
num = 2, args = 3
6

param statement

The param statement can be used to define arguments.
The param statement can be used in scripts, functions, and script blocks.

LinkString.ps1

param([string]$text1, [string]$text2)
$text1 + $text2
PS> .\LinkString.ps1 aaa bbb
aaabbb

Parameter types and default values

To specify the type of a parameter, use the form [type name]$parameter name.

To specify the default value of a parameter, use the form $parameter name = default value.

function GetString ([string]$text = "text", [int]$num = 3) {
    $text * $num
}
PS> GetString
texttexttext
PS> GetString One 1
One

Type shortcut

A type can have a full class name or a simplified form.

  • [swich]: False if the parameter is not specified, True if it is specified.
  • [ref]: Pass by reference.
  • [xml]: XML Other.

[switch] behavior

It is useful to use [switch] to switch the behavior.

function TestSwitch ([switch]$param) {
    Write-Host $param
}
PS> TestSwitch
False
PS> TestSwitch -param
True

Make a parameter mandatory

To make a parameter mandatory, use [parameter(mandatory)].

Since V3.0, you can use [Parameter(Mandatory)].

function SampleFunc ([Parameter(Mandatory)]$Param) {
    $Param
}

For V2.0, use [Parameter(Mandatory=$True)].

function SampleFunc ([Parameter(Mandatory=$True)]$Param) {
    $Param
}

Limit parameters

Use VaridateSet() to restrict parameters.
The Tab key will also be used for input completion.

You can limit the value of a parameter to one of a predetermined set of values.
In addition, you can use the Tab key to input completion.

script

param(
    [validateset("Cyan","Magenta","Yellow","Black")]$cmyk = "Cyan",
    [validateset("Red","Green","Blue")]$rgb = "Red"
)
 
Write-Host $cmyk
Write-Host $rgb

Execution example

PS> .\script.ps1 Black Blue # Input completion with SpaceKey+TabKey after ".ps1"
Black
Blue

Pipelines and Functions

Functions can also be integrated into pipelines.

Automatic variable $input

The automatic variable $input stores an enumerator of the pipeline (instead of an array).
Unlike normal arrays, it does not have access to the previous information.
If you want to treat $input as an array, you need to force it to be an array as @($input).
The following function differs from the automatic variable $args only in the $input part.

function Double {
    foreach ($arg in $input) { # Different!
        $arg * 2
    }
}

Unlike the case of the automatic variable $args, the parameters are specified using a pipe.

PS> 2,3 | Double
4
6

If you specify parameters like a non-pipeline function,
it will not work because the parameters are not received properly.

PS> Double 2,3
PS>

begin/process/end keywords

By using the begin/process/end keywords,
you can specify initialization, processing for each record, and cleanup.
Let’s focus on the “processing order” here.
The processing order in the begin/process/end keywords is as follows

function BeginProcessEnd ($id) {
    begin {
        Write-Host "Begin (ID:$id)"
    }
    process {
        Write-Host "Process $_ (ID:$id)"
        $_
    }
    end {
        Write-Host "End (ID:$id)"
    }
}

The processing order is “Begin all -> process the pipeline elements one by one -> then end all”.

PS> 1,2 | BeginProcessEnd 1 | BeginProcessEnd 2 | BeginProcessEnd 3
Begin (ID:1)
Begin (ID:2)
Begin (ID:3)
Process 1 (ID:1)
Process 1 (ID:2)
Process 1 (ID:3)
1
Process 2 (ID:1)
Process 2 (ID:2)
Process 2 (ID:3)
2
End (ID:1)
End (ID:2)
End (ID:3)

filter

You can use the filter keyword to create a function for the pipeline.
You can use the automatic variables $_ and $PSItem in the filter.

filter GetEven {
    if (!($_ % 2)) {
        $_
    }
}
PS> 1..10 | GetEven
2
4
6
8
10

YouTube

Click here for a video explanation.

Chapter 9 - Functions | Microsoft Docs

About Functions | Microsoft Docs

About Return | Microsoft Docs

Last modified October 11, 2022: update (8216439)