How to Return Two Values From a Function in PowerShell

You can return two values from a PowerShell function by outputting two pipeline objects, but returning one named object is usually safer and easier to maintain. A [pscustomobject] lets the caller access values by meaningful property names instead of fragile numeric indexes. This guide shows the recommended pattern, simpler ordered-value alternatives, and how to prevent accidental extra output.

How PowerShell Function Output Works

PowerShell functions do not have fixed “return slots” like functions in some other languages. Instead, they write objects to the success output stream, which flows through the pipeline.

That behavior has two important consequences:

  • A function can output more than one object.
  • The result of every statement can become function output, even when you do not write return.

For example, a direct expression, a cmdlet result, or an accidental diagnostic value can become an extra returned item. That is why a function expected to produce two values may appear to return three or more.

The return keyword makes the intended output and exit point explicit. Its syntax is:

return [<expression>]

In a normal function, return exits the current scope after sending its expression to the output stream. It does not erase objects the function already emitted before reaching that line.

Use a custom object when the two values have distinct meanings, such as a quotient and remainder, a status and message, or a user and ID.

A table helps you choose a shape before writing the function.

What the caller needs Best return shape How the caller reads it
Two values with meaningful names [pscustomobject] $result.Name
Two small values where position is guaranteed Two pipeline objects $first, $second = Get-Value
Several named groups or result sets Hashtable $Results['KeyName']
One array that must stay one pipeline object Unary comma array return (, $array)

Step 1: Give Each Result a Clear Property Name

Choose names based on what the data means, not its position. Quotient and Remainder are clearer than Value1 and Value2.

Keep calculations assigned to variables until you are ready to construct the final result. This avoids sending intermediate values down the success stream.

Step 2: Return a Single Custom Object

The following function divides two integers and returns the quotient and remainder as properties of one object:

function Get-DivisionResult {
    param(
        [int]$Dividend,
        [int]$Divisor
    )

    if ($Divisor -eq 0) {
        throw "Divisor cannot be zero."
    }

    $quotient = [int][math]::Floor($Dividend / $Divisor)
    $remainder = $Dividend % $Divisor

    return [pscustomobject]@{
        Quotient = $quotient
        Remainder = $remainder
    }
}

The function emits one object, not two unrelated pipeline items. That object contains two named values.

Step 3: Capture the Object and Read Its Properties

Assign the function call to a variable, then use dot notation to retrieve each value.

$division = Get-DivisionResult -Dividend 17 -Divisor 5
$division.Quotient
$division.Remainder

The output is 3 for the quotient and 2 for the remainder.

Returning one object with named properties makes a function’s output contract clear and prevents callers from depending on output order.

Other Ways to Return Two Values

PowerShell can return ordered values, named result groups, or a whole array as one pipeline object.

Return Two Ordered Pipeline Objects

For a short internal helper function, you can output two values in a known order.

function Get-NameAndId {
    return "build-agent-01", 42
}

Capture the name and ID with multiple assignment:

$name, $id = Get-NameAndId
$name
$id

This is concise, but it is easy to break. If the function later outputs a warning string, Boolean result, or another object before the intended values, $name and $id receive the wrong data.

Before using multiple assignment, verify these conditions:

  • The values are simple.
  • Their order is obvious and stable.
  • You control both the function and all its callers.
  • The function has no incidental output.

Return a Hashtable for Named Result Groups

A hashtable works well when a function returns several named collections or categories.

function Get-ScanSummary {
    return @{
        ESC1 = @("Issue-001", "Issue-002")
        ESC2 = @("Issue-003")
    }
}

Capture the hashtable and retrieve a value by its key.

$Results = Get-ScanSummary
$esc1Findings = $Results['ESC1']

The key must match a key returned by the function. For example, $Results['ESC1'] reads the result group stored under ESC1.

Hashtables are useful when property-style access is not a good fit, such as when keys are calculated dynamically or represent categories supplied by an external system.

Keep an Array Together as One Pipeline Object

PowerShell normally unwraps a returned collection and sends each member through the pipeline separately. If a function returns an array containing three numbers, a downstream command usually receives three pipeline objects.

When the caller must receive the entire array as one object, use the unary comma operator:

function Get-NumberSet {
    $numbers = 1, 2, 3
    return (, $numbers)
}

This sends the array as one pipeline object rather than sending 1, 2, and 3 separately.

Get-NumberSet | Measure-Object

Measure-Object receives one input object: the array itself. Without the unary comma, it would receive the array’s individual members.

This is different from returning two scalar values.

Prevent Extra Output and Scope Mistakes

Keep Status Messages Out of the Success Output Stream

A PowerShell function can return output produced during execution in addition to an explicit return value. For example, this direct command output can contaminate a result:

Test-Path -Path $Path

If the caller expects one custom object, the Boolean result from Test-Path becomes an unwanted additional pipeline item unless you store, suppress, or deliberately use it.

For status text that should appear to a person but should not be captured as a return value, use the Information stream. PowerShell supports Write-Information beginning in PowerShell 5.0.

Write-Information "Checking division input" -InformationAction Continue

That message uses the Information stream instead of the success output stream, so it does not become part of a variable such as $division.

Avoid using formatting commands such as Format-Table inside functions that return data. Formatting cmdlets produce formatting instructions for display, not clean objects for a caller to process.

Put return in the Scope You Mean to Exit

A return inside a script block used by a pipeline command may leave that script block rather than stop the surrounding function in the way you expect.

Use a language foreach loop when you need a clear early return from a function:

function Find-FirstEven {
    param(
        [int[]]$Numbers
    )

    foreach ($number in $Numbers) {
        if ($number % 2 -eq 0) {
            return $number
        }
    }

    return $null
}

The first even number ends the function immediately. A script block used with commands such as ForEach-Object has its own scope, so its control flow is easier to misunderstand.

Return Values From PowerShell Class Methods

PowerShell classes were added in PowerShell 5.0. Class methods differ from ordinary functions: they do not automatically send every statement result to the output stream. A class method returns only what you explicitly return.

Use return in a class method when the method needs to provide a result object:

class Divider {
    [pscustomobject] GetResult([int]$Dividend, [int]$Divisor) {
        if ($Divisor -eq 0) {
            throw "Divisor cannot be zero."
        }

        return [pscustomobject]@{
            Quotient = [int][math]::Floor($Dividend / $Divisor)
            Remainder = $Dividend % $Divisor
        }
    }
}

Call the method and access its properties the same way as a function result:

$division = [Divider]::new().GetResult(17, 5)
$division.Remainder

Use a class when you need state and related methods. For a small reusable helper, a regular function returning a custom object is usually simpler.

Test the Function’s Output Contract

Before another script depends on a function, verify both the number of emitted pipeline objects and the shape of the result.

$check = @(Get-DivisionResult -Dividend 17 -Divisor 5)
$check.Count

A result of 1 confirms that the function emitted one top-level output object.

$check[0].PSObject.Properties.Name

You should see Quotient and Remainder. If the count is greater than one, inspect the function for direct expressions, Write-Output, unassigned cmdlet results, formatting commands, or other statements that emitted unintended success-stream output.

Next, update one function to return a named [pscustomobject], then test that @(Your-Function).Count is 1. For the underlying rules for output, scope, collections, and return, read Microsoft’s about_Return documentation.

Frequently Asked Questions

Can I return two values in a PowerShell function?

Yes. A PowerShell function can output two separate pipeline objects with return $first, $second, or it can return one object that contains two properties. A [pscustomobject] is usually the better choice because callers can use descriptive names such as $result.Quotient and $result.Remainder.

How do I capture the result of executing a PowerShell function?

Assign the function call to a variable when the function returns one object.

$result = Get-DivisionResult -Dividend 17 -Divisor 5

Read its properties with dot notation, such as $result.Quotient. For two intentionally ordered pipeline values, use multiple assignment: $first, $second = Get-NameAndId.

Why is my PowerShell function returning an extra string or Boolean?

PowerShell sends statement results to the success output stream unless they are assigned, suppressed, or redirected. A direct Test-Path, a bare variable expression, or Write-Output can add an item before or after the value you intended to return. Use Write-Information for status messages that must not be captured with the function result.

Do I need to use the return keyword?

No. Ordinary PowerShell functions output the results of their statements even without return. Use return when you want an explicit exit point or want the function’s intended output to be obvious; it exits the current function, script, or script block scope.

How do I return an array without PowerShell splitting it into pipeline items?

Use return (, $array) to send the array as one pipeline object. The unary comma prevents PowerShell from unrolling the collection for the pipeline, which is useful when a downstream command must receive the full array as one grouped value.

How do I debug unexpected implicit output from a PowerShell function?

Use Write-Debug to display variables while the function runs. A function can emit output during execution as well as an explicit return value, so an unexpected object may come from another statement in the function.