PowerShell Return Values
Return values are the results a function sends back to the code that called it. You can store a return value in a variable and use it later.
A function returns its output
This function adds two numbers. Its output is the return value.
function Get-Sum {
param([int]$a, [int]$b)
$a + $b
}
$total = Get-Sum -a 3 -b 4
$totalReturn ends the function early
The return line sends a value back at once. Lines after it do not run for that call.
function Get-Result {
param([int]$Score)
if ($Score -ge 50) { return "pass" }
"fail"
}
Get-Result -Score 80
Get-Result -Score 20A function can return several values
Every value a function outputs is part of its return value. Join them into one line to print them together.
function Get-ThreeNumbers {
1
2
3
}
$numbers = Get-ThreeNumbers
$numbers -join ", "Example
function Get-Report {
param([int]$a, [int]$b)
$total = $a + $b
if ($total -ge 10) { return "big: $total" }
"small: $total"
}
Get-Report -a 7 -b 6
Get-Report -a 2 -b 3Key points
- Return value: the result a function sends back when it finishes.
- A function returns whatever it outputs, not only the line marked with return.
- Store a return value in a variable to use it in later lines.
- The return keyword sends a value back and ends the function at once.
- A function can output several values, and they come back as a list.
In this example, Get-Report adds its two numbers and stores the total. If the total is 10 or more, return sends back a big label at once. Otherwise the function outputs a small label, and each call prints its own label.
Note
a function with no output sends back nothing, so its variable stays empty.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Get-Sum return when it is called as Get-Sum -a 3 -b 4, if its body is $a + $b?