PowerShell: How to Return Multiple Values from Function


When creating a PowerShell function, you can only use the return statement once.

However, you can specify multiple values to return from the function by using the following syntax:

function Add-Multiply {
    Param([int]$first, [int]$second)

    $add_values = $first + $second
    $multiply_values = $first * $second
    
    return @{Add = $add_values; Multiply = $multiply_values}
}

This particular function takes two integer values as input and then returns the sum of the values along with the product of the values.

The following example shows how to use this syntax in practice.

Example: How to Return Multiple Values from Function in PowerShell

Suppose that we would like to create a function that will add and multiply two values.

For example, if we provide the numbers 3 and 7 as arguments then we would like to return the following values function the function:

  • Add: 3 + 7 = 10
  • Multiply: 3 * 7 = 21

We can use the following syntax to do so:

function Add-Multiply {
    Param([int]$first, [int]$second)

    $add_values = $first + $second
    $multiply_values = $first * $second
    
    return @{Add = $add_values; Multiply = $multiply_values}
}

The following screenshot shows how to use this syntax in practice:

PowerShell return multiple values from function

Notice that when we use the statement Add-Multiply 3 7 that the function returns the following output:

  • Add: 10
  • Multiply: 21

We are able to successfully create a function that returns two values.

Note that if we change the integers that we provide as arguments to the function, then the function will return the updated sum and products of the two numbers.

For example, suppose we use the statement Add-Multiply 10 6 instead:

The function now returns the following output:

  • Add: 16
  • Multiply: 60

Note: In this example we created a function that returned two values, but you can specify as many variables as you’d like after the return statement to return even more values.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply