Return Several Items From a PowerShell Function

Rohan Timalsina Jul 12, 2022
  1. Use Array to Return Several Items From a PowerShell Function
  2. Use PSCustomObject to Return Several Items From a PowerShell Function
  3. Use Hash Tables to Return Several Items From a PowerShell Function
Return Several Items From a PowerShell Function

A function is a collection of one or more PowerShell commands and scripts. It can be executed multiple times in a script by simply calling its name.

As a result, it increases the usability and readability of the script. The return keyword in PowerShell exits a function or script block and is used to return a value from a function.

This tutorial will teach you to return multiple values from a function in PowerShell.

Use Array to Return Several Items From a PowerShell Function

The following example returns a single value from a function sum.

Code:

function sum()
{
$a = 4
$b =6
$c=$a+$b
return $c
}
sum

Output:

10

To return multiple values from a PowerShell function, you can return an array of objects. The following example returns the multiple values from a function num using an array.

Code:

function num()
{
$a = 4,5,6
return $a
}
$b=num
Write-Host "The numbers are $($b[0]),$($b[1]),$($b[2])."

Output:

The numbers are 4,5,6.

Use PSCustomObject to Return Several Items From a PowerShell Function

You can also create a PSCustomObject and return multiple items from a function in PowerShell. The following example creates a PSCustomObject $obj inside the function named user and returns multiple values.

Code:

function user()
{
$obj = [PSCustomObject]@{
    Name = 'Rohan'
    Age = 21
    Address = 'UK'
}
return $obj
}
$a=user
Write-Host "$($a.Name) is $($a.Age) and lives in $($a.Address)."

Output:

Rohan is 21 and lives in UK.

Use Hash Tables to Return Several Items From a PowerShell Function

The hash table is a compact data structure that stores each value using a key. It is also called a dictionary or associative array.

Hash tables have Keys and Values properties in PowerShell. The keys and values can have any .NET object type.

You can create a hash table in PowerShell using @{}. The keys and values are placed in the {} brackets.

The syntax to create a hash table is as follows.

@{ <key> = <value>; [<key> = <value> ] ...}

The following example uses the hash table to return multiple values from a function named user.

Code:

function user()
{
$hash = @{ Name = 'Rohan'; Age = 21; Address = 'UK'}
return $hash
}
$a=user
Write-Host "$($a.Name) is $($a.Age) and lives in $($a.Address)."

Output:

Rohan is 21 and lives in UK.

Now you know different methods to return multiple items from a function in PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Function