Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 34 ยท Functions and Scripts

Functions and Parameters

Write PowerShell functions with param blocks, defaults, typed and switch parameters, and learn why return is not the only way a function gives output.

A function gives a name to a piece of work so you can run it again with different inputs. In PowerShell, functions are as important as in any language, but they have one rule that surprises almost everyone: a function does not return a single value. It writes everything that reaches its output stream, and the caller gets all of it.

This lesson covers declaring functions, passing parameters in the several ways PowerShell allows, defaults, type conversion and switch parameters, and then that output rule and how to avoid accidental output. The PowerShell shown is read-only. The runnable examples are JavaScript stand-ins, labeled as such.

A first function

Declare a function with the function keyword, a name and a script block. Use the verb-noun naming from Cmdlets and the Verb-Noun Pattern.

POWERSHELL
function Get-Greeting {
    param(
        [string]$Name = 'world'
    )
    "Hello, $Name"
}

Get-Greeting                    # Hello, world
Get-Greeting -Name Ada          # Hello, Ada
Get-Greeting Ada                # positional: Hello, Ada

The param( ) block declares the parameters. Each one can have a type in square brackets and a default value after =. The function must be defined before the line that calls it, because a script runs top to bottom.

You call functions the way you call commands: name first, then arguments separated by spaces. There are no parentheses and no commas between arguments. This is the most common beginner error:

POWERSHELL
function Add-Numbers { param([int]$A, [int]$B) $A + $B }

Add-Numbers 2 3        # 5     correct
Add-Numbers(2, 3)      # wrong: passes one array (2, 3) as the first argument
Add-Numbers 2, 3       # also wrong: the comma makes one array again

Parentheses are for grouping expressions, so use them only when an argument is itself an expression, as in Get-Greeting -Name (Get-Date).DayOfWeek.

Parameters in depth

Parameters give you several features without extra code.

POWERSHELL
function New-Report {
    param(
        [Parameter(Position = 0)]
        [string]$Title,

        [int]$Rows = 10,

        [string[]]$Columns = @('Name', 'Size'),

        [switch]$Summary
    )
    "Report '$Title' with $Rows rows and columns: $($Columns -join ', ')"
}

New-Report 'Disk' -Rows 5
New-Report -Title 'Disk' -Columns Name, Size, Owner
  • Named or positional. Callers can write -Rows 5 or rely on order. Names can be shortened to any unambiguous prefix, like -Ro 5, but spell them out in scripts.
  • Types convert. [int]$Rows converts the string '5' to 5 and rejects 'five' with an error before your code runs.
  • Arrays. [string[]] accepts a comma-separated list.
  • Defaults. The default can be any expression, such as $Path = (Get-Location).Path. Defaults apply only when the caller did not supply the parameter.

If you do not write a param block, the arguments land in the automatic array $args. That works for tiny helpers, but a named parameter is clearer, validated and discoverable with tab completion.

Switch parameters

A [switch] parameter is a flag. It is $false when absent and $true when the caller writes its name, with no value needed.

POWERSHELL
function Get-Message {
    param([string]$Text = 'ready', [switch]$Loud)
    if ($Loud) { $Text.ToUpper() } else { $Text }
}

Get-Message                       # ready
Get-Message -Loud                 # READY
Get-Message -Loud:$false          # ready  (colon form passes a value)

The colon form -Loud:$false matters when you forward a value from another variable. Test a switch with if ($Loud) or $Loud.IsPresent. Do not give a switch a default of $true, because the caller then has no natural way to turn it off.

When one function must pass its parameters on to another command, build a hashtable and splat it, as shown in Arrays and Hashtables.

How output really works

Here is the rule: every expression whose value is not assigned, piped or redirected writes its result to the function's output. The return keyword is only a shortcut that writes a value and exits right away.

POWERSHELL
function Get-Numbers {
    1
    2
    return 3
    4                 # never reached
}

Get-Numbers           # 1, 2, 3 as three separate objects

These two functions return the same thing:

POWERSHELL
function A { return 'x' }
function B { 'x' }

If a function writes several values, the caller receives an array. If it writes one, the caller receives that one object, and if it writes nothing the result is nothing ($null).

Where function output comes from

Bare expressions Any unassigned value is output.
return Writes a value, then exits.
Assignment $x = ... captures a value, so it is not output.

Output is a stream of objects, not one return value.

1 / 2

The leakage trap

The classic bug appears when a method returns a value you did not ask for. ArrayList.Add returns the index of the new item, and a function that does not discard it adds numbers to its own output.

POWERSHELL
function Get-Names {
    $list = [System.Collections.ArrayList]::new()
    $list.Add('Ada')        # emits 0 into the output!
    $list.Add('Grace')      # emits 1
    $list
}

Get-Names     # 0, 1, Ada, Grace  (not what you wanted)

The fix is to silence the call with [void], assign to $null, or use a List[T], whose Add returns nothing. Other common leaks are New-Item printing the item it created, and HashSet[T].Add, which returns a Boolean.

Messages are different. Write-Host prints to the host and does not join the output, so it is for human-readable status only, never for data. Use Write-Output (or just the bare expression) for data and Write-Verbose for optional detail, as covered in Advanced Functions.

POWERSHELL
function Test-Log {
    Write-Host 'working...'    # shown on screen, not captured
    'result'                   # the actual output
}
$value = Test-Log               # screen shows working..., $value is 'result'

Scope in functions

A function runs in its own scope. It can read variables from the caller, but assigning a variable inside the function creates a new local one and leaves the caller's variable alone.

POWERSHELL
$count = 1
function Add-One { $count = $count + 1; $count }
Add-One      # 2
$count       # still 1

Pass data in through parameters and out through output. Avoid reaching for $script: or $global: variables unless you truly need shared state.

A model of the output stream

The stand-in below does not run PowerShell. It builds a tiny model of function output: a function gets an emit function, calling it writes to the stream, and return emits and stops. It shows the leakage trap and its fix with the same logic.

JS Output leakage, modeled in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The emit and ret functions are a model. Real PowerShell writes to a pipeline of objects, not an array, and downstream commands can begin work before the function finishes.

Here is a second model, this time of parameter binding with defaults and a switch. A parameter spec table describes each parameter, and the binder fills in positional values, named values and defaults.

JS Binding arguments to parameters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The binder here is a simplified model. Real PowerShell also matches abbreviated names, parameter sets, pipeline input and validation attributes, which the next lesson adds.

PowerShell 7 tooling and Windows PowerShell 5.1 treat functions the same way. The leakage rule is the same in every version, which is why experienced scripters assign or [void] any call whose result they do not need.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you correctly call a function declared as function Add-Numbers { param([int]$A, [int]$B) $A + $B } with the values 2 and 3?

    Arguments are separated by spaces. Parentheses with a comma, or a comma without parentheses, build a single array passed as the first argument.
  2. 2. What does a function return when it writes the values 1, 2 and 3 to its output?

    All output counts, not just the value after return. Several outputs reach the caller as an array.
  3. 3. A function calls $list.Add('x') on an ArrayList and the caller gets an unexpected number. Why?

    ArrayList.Add returns an index. Use [void], $null = or a List[T] to keep it out of the output.
  4. 4. Which line turns a switch parameter named -Loud off when it comes from a variable?

    The colon form attaches a value to a switch. Without the colon, $false would be treated as the next positional argument.

Summary

  • Declare functions with function Verb-Noun { param(...) ... } and call them without parentheses or commas.
  • Parameters can be typed, have defaults, accept arrays and be positional or named.
  • A [switch] is a flag: absent is $false, present is $true, and -Name:$false sets it explicitly.
  • Functions output every unassigned value. return writes and exits, it is not the only way to return data.
  • Silence accidental output with [void], $null = or a type whose method returns nothing, such as List[T].
  • Functions have their own scope: they read the caller's variables but assign local copies.

Next, make your functions behave like real cmdlets with Advanced Functions.