0
0
PowerShellscripting~5 mins

Return values in PowerShell

Choose your learning style9 modes available
Introduction

Return values let a function send back a result after it finishes. This helps you use that result later in your script.

When you want a function to give back a calculation result.
When you need to check if a task succeeded or failed.
When you want to reuse a value from a function in other parts of your script.
When you want to organize your script into smaller, reusable pieces.
Syntax
PowerShell
function FunctionName {
    # Do something
    return <value>
}

The return keyword sends a value back from the function.

If you don't use return, PowerShell returns the last output automatically.

Examples
This function adds two numbers and returns the sum.
PowerShell
function Get-Sum {
    param($a, $b)
    return $a + $b
}
This function returns a simple greeting string.
PowerShell
function Get-Greeting {
    return "Hello, World!"
}
This function returns a random number between 1 and 10 without using return explicitly.
PowerShell
function Get-RandomNumber {
    Get-Random -Minimum 1 -Maximum 11
}
Sample Program

This script defines a function that multiplies two numbers and returns the product. Then it calls the function with 4 and 5, stores the result, and prints it.

PowerShell
function Multiply-Numbers {
    param($x, $y)
    return $x * $y
}

$result = Multiply-Numbers -x 4 -y 5
Write-Output "The result is $result"
OutputSuccess
Important Notes

Using return stops the function immediately and sends back the value.

Functions can return any type of data: numbers, strings, objects, or even arrays.

Summary

Return values let functions send results back to the caller.

Use return to specify what to send back.

You can use the returned value later in your script for more work.