I agree with @Christian, and I add another solution.

First you can return using an array explicitly or implicitly:

  1. explicitly

    function ExplicitArray ()
    {
      $myArray = @()
    
      $myArray += 12
      $myArray += "Blue"
    
      return ,$myArray
    }
    
    Clear-Host
    $a = ExplicitArray
    Write-Host "values from ExplicitArray are a[0]) and a[1])"
    
  2. implicitly

    function ImplicitArray ()
    {
      Write-Output 12
    
      Write-Output "Blue"
      return "green"
    }
    
    $b = ImplicitArray
    Write-Host "values from ImplicitArray are b[0]), b[1]) and b[2])"
    

Second you can return a custom object:

  1. Short form

    function ReturnObject ()
    {
      $value = "" | Select-Object -Property number,color
      $value.Number = 12
      $value.color = "blue"
      return $value
    }
    $c = ReturnObject
    Write-Host "values from ReturnObject are c.number) and c.color)"
    
  2. School form

    function SchoolReturnObject ()
    {
      $value = New-Object PsObject -Property @{color="blue" ; number="12"}
      Add-Member -InputObject $value –MemberType NoteProperty –Name "Verb" –value "eat"
      return $value
    }
    $d = SchoolReturnObject
    Write-Host "values from SchoolReturnObject are d.number), d.color) and d.Verb)"
    

Third using argument by reference:

function addition ([int]y, [ref]$R)
{
 $Res = y
 $R.value = $Res
}

$O1 = 1
O3 = 0
addition O2 ([ref]$O3)
Write-Host "values from addition o2 is $o3"
Answer from JPBlanc on Stack Overflow
Top answer
1 of 6
109

I agree with @Christian, and I add another solution.

First you can return using an array explicitly or implicitly:

  1. explicitly

    function ExplicitArray ()
    {
      $myArray = @()
    
      $myArray += 12
      $myArray += "Blue"
    
      return ,$myArray
    }
    
    Clear-Host
    $a = ExplicitArray
    Write-Host "values from ExplicitArray are a[0]) and a[1])"
    
  2. implicitly

    function ImplicitArray ()
    {
      Write-Output 12
    
      Write-Output "Blue"
      return "green"
    }
    
    $b = ImplicitArray
    Write-Host "values from ImplicitArray are b[0]), b[1]) and b[2])"
    

Second you can return a custom object:

  1. Short form

    function ReturnObject ()
    {
      $value = "" | Select-Object -Property number,color
      $value.Number = 12
      $value.color = "blue"
      return $value
    }
    $c = ReturnObject
    Write-Host "values from ReturnObject are c.number) and c.color)"
    
  2. School form

    function SchoolReturnObject ()
    {
      $value = New-Object PsObject -Property @{color="blue" ; number="12"}
      Add-Member -InputObject $value –MemberType NoteProperty –Name "Verb" –value "eat"
      return $value
    }
    $d = SchoolReturnObject
    Write-Host "values from SchoolReturnObject are d.number), d.color) and d.Verb)"
    

Third using argument by reference:

function addition ([int]y, [ref]$R)
{
 $Res = y
 $R.value = $Res
}

$O1 = 1
O3 = 0
addition O2 ([ref]$O3)
Write-Host "values from addition o2 is $o3"
2 of 6
56

Maybe I am misunderstanding the question but isn't this just as simple as returning a list of variables, and the caller simply assigns each to a variable. That is

> function test () {return @('a','c'),'b'}
> b = test

$a will be an array, and $b the letter 'b'

> b
b
🌐
Delft Stack
delftstack.com › home › howto › powershell › return several items from a powershell function
How to Return Several Items From a PowerShell Function | Delft Stack
February 2, 2024 - Now, you can call the function and retrieve the custom object containing multiple values. $result = Get-MultipleValues -Value1 'Rohan' -Value2 21 -Value3 'UK' Write-Output "Values returned from the function:" foreach ($value in $result) { Write-Output $value } ... As we can see, the PowerShell code above introduces a function named Get-MultipleValues.
Discussions

How to return multiple properties of an object into another function?
I have the following script that fetches reports from a URI and displays the datasource(s) username. However, we'd like to get the name of the reports so we know what datasource username is associated with what report for tracking purposes. … More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
Struggles in understanding how to return multiple values from PowerShell script.
output each variable value to a corresponding txt file. Use the GetVariable command to set a variable value equal to the contents of that file. Rinse and repeat. More on reddit.com
🌐 r/kaseya
4
2
July 26, 2024
Passing multiple parameters to a function and returning multiple values
Hi All, I am trying to rewrite an existing program to use a function since I need to run the same steps more than once. I am running into issues passing values in and out of the function. My input file has three columns IDNum,UPN,Role. I am updating the script variables and creating a list ... More on forums.powershell.org
🌐 forums.powershell.org
3
0
August 26, 2022
Return multiple Values from function
Hi ! I have 2 function in my Script powershell. One get the value of the user and the other one use the values. I found a way to return multiple values from a function (Table).It’s working perfectly .But the values are not recognized by the second function ($Return[1] is empty). More on community.spiceworks.com
🌐 community.spiceworks.com
4
10
May 4, 2019
🌐
Day3bits
day3bits.com › 2023-12-08-return-multiple-objects-from-a-powershell-function
Return Multiple Objects from a PowerShell Function | Day 3 Bits
December 8, 2023 - Alternatively, we can save them as new variables in the main function, making things even easier for repeated use. ... That's it! That's the tip. Return multiple named objects from a function but using a hash table to name and store them.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 705532 › how-to-return-multiple-properties-of-an-object-int
How to return multiple properties of an object into another function? - Microsoft Q&A
# lists all the reports on the server that are available to your user account Function listReports($baseURL) { $reports = Invoke-RestMethod -UseDefaultCredentials -uri "$baseURL/api/v2.0/CatalogItems" $reports.value | Where-Object {$_.Type -eq "PowerBIReport"} | foreach { #Write-Host ("{0} {1} {2}" -f $_.Id, $_.Name, $_.Path) return $_.Id } } Function getDataSources($baseURL, $reportID) { $sources = Invoke-RestMethod -UseDefaultCredentials -uri "$baseURL/api/v2.0/PowerBIReports($reportID)/DataSources" if ($sources.value -is [array]) { return $sources.value } else { return @($sources.value) } }
🌐
ByteInTheSky
byteinthesky.com › home › powershell › how to return multiple values from function
How to Return Multiple Values from Function - ByteInTheSky
April 7, 2023 - 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. 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.
🌐
GitHub
github.com › PowerShell › PowerShell › discussions › 18601
How do cmdlets return multiple objects as an array? · PowerShell/PowerShell · Discussion #18601
What can get tricky is that a given command can situationally produce either one or multiple outputs, depending on inputs and runtime conditions, so the engine may return either a single object or an array. @(...), the array-subexpression operator, is designed to eliminate this ambiguity, if needed: By wrapping a command in @(...), PowerShell ensures that its output is always collected as [object[]] - even if the command happens to produce just one output object or even none:
Author   PowerShell
🌐
Reddit
reddit.com › r/kaseya › struggles in understanding how to return multiple values from powershell script.
r/kaseya on Reddit: Struggles in understanding how to return multiple values from PowerShell script.
July 26, 2024 -

I have a PowerShell script that returns an array of 6 properties.

Here's a simplified version:

$output = @()
...rest of code...
$output += [PSCustomObject]@{
Property1 = $someBool
Property2 = $someValue1
Property3 = $someValue2
Property4 = $someValue3
Property5 = $someValue4
Property6 = $someValue5
}

return $output | Format-Table -AutoSize

Using executePowershellCommand64BitSystem along with updateSystemInfo, how can I get all the values from the output and apply them to custom fields for the agent(s)? I've read the documentation, but it's not very straightforward. Then again, I could just be missing something.

EDIT: Maybe something like this? (can't test, need approval first):

writeFile("VSASharedFiles\Script.ps1", "C:\Scripts\Script.ps1", "All Operating Systems", "Halt on Fail")
executePowershellCommand64BitSystem("C:\Scripts\Script1.ps1", " ", true, "All Operating Systems", "Halt on Fail")
getVariable("Constant Value", "#global:someBool#, "someBool", "All Operating Systems", "Halt on Fail")
getVariable("Constant Value", "#global:someValue1#, "someValue1", "All Operating Systems", "Halt on Fail")
<similar for the remaining variables>
updateSystemInfo("CustomField1", "#someBool#", "All Operating Systems", "Halt on Fail")
updateSystemInfo("CustomField2", "#someValue1#", "All Operating Systems", "Halt on Fail")
<similar for the remaining values>

Top answer
1 of 2
2
output each variable value to a corresponding txt file. Use the GetVariable command to set a variable value equal to the contents of that file. Rinse and repeat.
2 of 2
1
This is pretty trivial. Return the array as a delimited string. Have a generic powershell script that returns "Element X" from a delimited string - pass the full string, delimiter char, and position as args and get the positional value via STDOUT. One script does the main data work, the second script - called multiple times, parses individual values. Our audit collects over 300 values every day, plus custom data that our MSPs need for special reporting. Often we write multiple delimited or named (name=value, name2=value2) data to a single custom field. That's helpful when we need to reference the data from an independent process. We can either extract the specific value from a delimited list or perform "if contains" logic. We even have a tool that can run from the RMM and request data from an INI format file, so if your app / script can write multiple data values to an INI format file, we can selectively read data from any section:value. Of course, if your end goal is to simply populate custom fields, then the API is your best friend. Our audit does this daily - between the full data collection and pushing values back to 30-40 custom fields on each agent - it takes less than 30-seconds to run. Now all of the other apps have all the data they need at their disposal, either in custom fields or in a cache file on the device that holds ALL of the data collected.
Find elsewhere
🌐
PowerShell Forums
forums.powershell.org › powershell help
Passing multiple parameters to a function and returning multiple values - PowerShell Help - PowerShell Forums
August 26, 2022 - Hi All, I am trying to rewrite an existing program to use a function since I need to run the same steps more than once. I am running into issues passing values in and out of the function. My input file has three columns IDNum,UPN,Role. I am updating the script variables and creating a list ...
🌐
Softwarepronto
softwarepronto.com › 2020 › 10 › powershell-inadvertently-returning.html
Jan David Narkiewicz (Developer): PowerShell: Inadvertently Returning Multiple Values from a Function
Microsoft's documentation on returning values from a function can be found at: About Return. This documentation contains as set of comprehensive examples that clarify the behavior of the return keyword and how variables/statements are returned from PowerShell functions: ... Load more... ... PowerShell: Inadvertently Returning Multiple Value...
🌐
PowerShell Test-Path
powershellfaqs.com › powershell-functions-return-values
PowerShell Functions: Return Values and Multiple Values
July 6, 2024 - You can return multiple values from a PowerShell function using an array, hashtable, or complex objects.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_return
about_Return - PowerShell | Microsoft Learn
Utilizing a unary expression you can send your return value down the pipeline as a single object as illustrated by the following example. function Test-Return { $array = 1,2,3 return (, $array) } Test-Return | Measure-Object
Top answer
1 of 4
10

Hi ! I have 2 function in my Script powershell. One get the value of the user and the other one use the values. I found a way to return multiple values from a function (Table).It’s working perfectly .But the values are not recognized by the second function ($Return[1] is empty). Do anyone knows the problem of my code ?

Thanks

$Button2.Add_Click({test1})

$BtnConfirm.Add_Click({test2})

Function test1($Folders,$CheckValue, $UserResearch)
{   

    $Folders = $TextBoxLink.Text
    $CheckValue = $True

    if($CheckBoxYes.Checked -eq $true)
    {
        $CheckValue = $True
    }

    elseif($CheckBoxNo.Checked -eq $true)
    {
        $CheckValue = $False
    }

    $UserResearch = $TextBoxUser.Text
    
    Return $Folders,$CheckValue,$UserResearch

}

$Return = test1

Function test2($Return)
{
   
    ###################################### SI FILTRE ################################
    
    if($Return[1] -eq $True)
    {
        New-Item -Name "superCaMarche.txt" -Path \\srv-files\RNS_Services\Informatique\Test_Depraz -Value $CheckValue
        
        #Récupère le nom de domaine
        $Domain = (Get-ADDomain).NetBIOSName

            #Sotck dans une variable les objects du dossier donné par l'utilisateur 
            $Folders = Get-Item -Path $Path

                #Parcours le dossier ou l'arborescence
                ForEach ($Folder in $Folders)
                {   

                    #Récupère les droits sur un dossier et les stocks
                    $ACLs = Get-Acl $Folder.FullName | ForEach-Object { $_.Access }

                    #Parcours tous les droits sur un dossier
                    ForEach ($ACL in $ACLs)
                    {  
    
                    #Controle si il existe bien des droits  
                    If ($ACL.IdentityReference -match "\\")
                        {   
                        #Controle si le dossier possède des droits lié au domaine
                        If ($ACL.IdentityReference.Value.Split("\")[0].ToUpper() -eq $Domain.ToUpper())
                            { 
                            #Entre dans une variable le nom du groupe AD
                             $Name = $ACL.IdentityReference.Value.Split("\")[1]

                                #Vérifie que l'object récupéré est bien un groupe
                                If ((Get-ADObject -Filter 'SamAccountName -eq $Name').ObjectClass -eq "group")
                                {   

                                #Parcours les informations du groupe récupéré 
                                ForEach ($User in (Get-ADGroupMember $Name -Recursive | Select -ExpandProperty Name))
                                    {   $Result = New-Object PSObject -Property  @{
                                            Path = $Folder.Fullname
                                            Group = $Name
                                            User = $User
                                            FileSystemRights = $ACL.FileSystemRights
                                            AccessControlType = $ACL.AccessControlType
                                            Inherited = $ACL.IsInherited
                                        }
                                        $Result | Select group,FileSystemRights,AccessControlType,Inherited, User |Where-Object{$User.Equals($UserResearch)} |export-csv \\srv-files\RNS_Services\Informatique\Test_Depraz\"$UserResearch".csv -Append
                                        #$Result | Select Path,Group,User,FileSystemRights,AccessControlType,Inherited
                                    }
                                }
                            }
                        }
                    }
                }
           }       
2 of 4
1

Either return a string that you then parse out separate values using delimiters, or return a data structure like an array.

Powershell - Pass array from one function to another Programming & Development
All right, so the basics: I have a 1 button, the first button calls a function which returns an array. I have another button that needs to use the array from the first function. I've tried calling the first function from the second function and have a return statement for my array. The code for this is pretty long, but in a general sense it's just how to I return an array from one function and then use it in a second function. I've been Googleing all yesterday and haven't found anything. B…
🌐
Zeleskitech
zeleskitech.com › 2015 › 12 › 09 › returning-multiple-values-from-a-powershell-function
Returning multiple values from a PowerShell function
December 9, 2015 - I tried 100 different ways of building nested json but all of them failed to expand the object correctly. I posted to Reddit and a kind user pointed me to a simple fix. The cmdlet ConvertTo-Json has a […] Read more ... I’ve been working on a pretty large project in powershell that involves ...
🌐
w3tutorials
w3tutorials.net › blog › how-to-return-several-items-from-a-powershell-function
How to Return Multiple Values from a PowerShell Function: Extracting SVN External Definition Data — w3tutorials.net
The loop above outputs a [PSCustomObject] for each valid external. PowerShell automatically collects these objects into an array, which the function returns.
🌐
Idera
community.idera.com › database-tools › powershell › powertips › b › tips › posts › returning-multiple-values
Returning Multiple Values - Power Tips - Power Tips - IDERA Community
October 4, 2014 - A PowerShell function can return multiple values. To receive them, simply assign the result to multiple variables: function Get-DateTimeInfo { # Value 1
🌐
Reddit
reddit.com › r/powershell › returning multiple objects within a class
r/PowerShell on Reddit: Returning multiple objects within a class
September 5, 2019 -

Hello,

I'm working with classes right now and try to implement classes in my functions. I have a simple class which takes path and return object with name,date,workstation etc. I don't know much about PS classes so my question is:

Should class only return one object at time or could I implement foreach statement and return multiple object within a class? So if I run [MyClass]::new($path) should it return just one object or could I irritate through $path variable and return multiple objects? What is the best practice?

It this sounds stupid, I get that but no dev background so need to learn from my mistakes :)

Thanks :)

🌐
TheITBros
theitbros.com › powershell › using return statement in powershell functions and scripts – theitbros
Using Return Statement in PowerShell Functions and Scripts – TheITBros
January 5, 2026 - Function GetServiceAndProcess { return ` $( Get-Service -ErrorAction SilentlyContinue | Select-Object -First 5 ), $( Get-Process -ErrorAction SilentlyContinue | Select-Object -First 5 ) } Invoke the PowerShell function and save the results in the $result variable.
🌐
Anand, the Architect
anandthearchitect.com › 2014 › 03 › 18 › powershell-how-to-return-multiple-values-from-a-function
PowerShell: How to return multiple values from a Function? – Anand, the Architect
May 2, 2014 - Function Get-UserInfo($username) { #Create an hashtable variable [hashtable]$Return = @{} Import-Module ActiveDirectory $ADUser = Get-ADUser -Identity $username -Properties Department, employeeNumber,l,Manager #Assign all return values in to hashtable $Return.Name = $ADUser.name $Return.EmployeeNo = $ADUser.employeeNumber $Return.Location = $ADUser.l $Return.Department = $ADUser.department $Return.Manager = ( Get-ADUser $ADUser.manager ).Name #Return the hashtable Return $Return }
Top answer
1 of 4
38

In your powershell script you can build an Hashtable based on your necessity:

[hashtable]$Return = @{} 
$Return.ReturnCode = [int]1 
$Return.ReturnString = [string]"All Done!" 
Return $Return 

In C# code handle the Psobject in this way

 ReturnInfo ri = new ReturnInfo();
 foreach (PSObject p in psObjects)
 {
   Hashtable ht = p.ImmediateBaseObject as Hashtable;
   ri.ReturnCode = (int)ht["ReturnCode"];
   ri.ReturnText = (string)ht["ReturnString"];
 } 

//Do what you want with ri object.

If you want to use a PsCustomobject as in Keith Hill comment in powershell v2.0:

powershell script:

$return = new-object psobject -property @{ReturnCode=1;ReturnString="all done"}
$return

c# code:

ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
   {
     ri.ReturnCode = (int)p.Properties["ReturnCode"].Value;
     ri.ReturnText = (string)p.Properties["ReturnString"].Value;
   }
2 of 4
7

CB.'s answer worked great for me with a minor change. I did not see this posted anywhere (in regards to C# and PowerShell) so I wanted to post it.

In my PowerShell script I created created a Hashtable, stored 2 values in it (a Boolean and an Int) and then converted that into a PSObject:

$Obj = @{}

if($RoundedResults -ilt $Threshold)
{
    $Obj.bool = $true
    $Obj.value = $RoundedResults
}
else
{
    $Obj.bool = $false
    $Obj.value = $RoundedResults
}

$ResultObj = (New-Object PSObject -Property $Obj)

return $ResultObj

And then in my C# code I did the same thing that CB. did but I had to use Convert.ToString in order to successfully get the values back:

ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
   {
     ri.ReturnCode = Convert.ToBoolean(p.Properties["ReturnCode"].Value;)
     ri.ReturnText = Convert.ToString(p.Properties["ReturnString"].Value;)
   }

I found the answer to this via the following StackOverflow post: https://stackoverflow.com/a/5577500

Where Kieren Johnstone says:

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

🌐
A Girl Among Geeks
agirlamonggeeks.com › home › how do you return a value from a function in powershell?
How Do You Return a Value From a Function in PowerShell?
July 4, 2025 - For example, consider the following function which outputs multiple values: “`powershell function Get-Numbers { 1 2 3 } “` Calling `Get-Numbers` returns an array of three integers, even though there is no explicit `return` statement. The `return` keyword in PowerShell serves two main purposes: to output a value and to immediately exit the function. However, because PowerShell outputs all un-captured pipeline objects as return values, the use of `return` is often optional unless you want to terminate function execution prematurely.