🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Function Output

Function output is every value a function sends out while it runs. The caller receives all of it as the function's return value.

A stray string joins the return value

The word working was only meant as a note. It still becomes part of what the caller receives.

function Get-DemoTotal {
    param([int]$a, [int]$b)
    "working"
    $a + $b
}
$result = Get-DemoTotal -a 3 -b 4
$result -join ", "

Write-Output and implicit output match

The first function sends its value with Write-Output. The second function just states its value, and the caller sees the same result.

function Get-DemoFirst {
    Write-Output "one"
}
function Get-DemoSecond {
    "two"
}
Get-DemoFirst
Get-DemoSecond

Wrap a call in @() to count safely

A single value on its own is not a collection. Wrapping the call always gives a collection, even for one value or none.

function Get-DemoOne { "only" }
function Get-DemoMany { "a"; "b" }
function Get-DemoNone { }
$one = Get-DemoOne
"One is array: " + ($one -is [array])
$wrapped = @(Get-DemoOne)
"Wrapped count: " + $wrapped.Count
$many = @(Get-DemoMany)
"Many count: " + $many.Count
$none = @(Get-DemoNone)
"None count: " + $none.Count

Example

function Get-DemoEvens {
    param([int[]]$Numbers)
    foreach ($n in $Numbers) {
        if ($n % 2 -eq 0) { $n }
    }
}
$evens = @(Get-DemoEvens -Numbers 1, 2, 3, 4, 5, 6)
"Evens: " + ($evens -join ", ")
"Count: " + $evens.Count

Key points

  • Return value: everything a function outputs becomes its return value.
  • Stray output: a value sent out by accident inside a function still joins the return value.
  • Use Write-Output to send a value out of a function on purpose.
  • Implicit output: a value on its own line is sent out just like Write-Output sends it.
  • Use @() around a call to always get a collection you can count.

In this example, the function sends out only the even numbers, one per line of its body. The caller wraps the call in @(), so it can join the values into one line and count them.

Note

A function with no output returns nothing, and @() around it gives an empty collection with a count of 0.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A function meant to return a total also states the word working inside its body. What does the caller receive?