How to Return Multiple Values from Function

Problem

Many commands in PowerShell return a single object or value, but sometimes you need multiple values. This is especially true when working with functions. In this article, we’ll show you how to return multiple values from PowerShell function.

Solution

The most common way to do this is by using the Return keyword and specifying the values you want to return.

Let’s take a look at some examples.

Specifying All the Values to Return

This is the most straightforward way to return multiple values. We specify all the values along with return keyword, then in the caller code we destructure all the values before using them accordingly.


Function Test()
{
    $FirstName = "John"
    $LastName = "Doe"

    return $FirstName, $LastName
}

$firstName, $lastName = Test
$firstName
$lastName

Below is the output if we execute above script.

output from Specifying All the Values to Return example

Return Values Using HashTable

We can also wrap the values into a HashTable by specifying key-value pairs. In this case, the key is the property we are going to use. Then, we return the HashTable.


Function Test() {
    $FullName = @{
        FirstName = "John"
        LastName  = "Doe"
    }

    return $FullName
}

$fullName = Test
foreach ($key in $fullName.Keys) {
    Write-Host "$key is $($fullName[$key])"
}

Below is the output if we execute above script.

Output from Return Values Using HashTable example

Return Values Using PSCustomObject

We can also return values using PSCustomObject. This is similar with using HashTable, but we need to add PSCustomObject keyword before @ symbol. Other than that, we specify the object property and its value. In order to get the value, the caller code only needs to specify object property and use it accordingly.


Function Test() {    
    $FullName = [PSCustomObject]@{
        FirstName = "John"
        LastName  = "Doe"
    }

    return $FullName
}

$fullName = Test
Write-Host "FirstName is $($fullName.FirstName)"
Write-Host "LastName is $($fullName.LastName)"

Below is the output if we execute above script.

Output from Return Values Using PSCustomObject example

Conclusion

There are three ways we can use to return multiple values from a function, which are specifying all the values, using HashTable or using PSCustomObject. I hope this article helps you to learn how to return multiple values from a function in PowerShell.