First, use the array sub-expression operator @( ... ). This operator returns the result of one or more statements as an array. If there is only one item, the array has only one member.

$returnArray = @( Get-ChildItem "F:\PowerShell\A" )

Use Write-Output with the switch -NoEnumerate to prevent PowerShell from un-rolling the array.

Write-Output -NoEnumerate $returnArray

You can also effectively achieve the same result using Write-Output without using the -NoEnumerate by using the following syntax below.

Write-Output ,$returnArray

The comma in front of $returnArray effectively creates a new array with $returnArray as its only element. PowerShell then un-rolls this new single-element array, returning the original $returnArray intact to the caller.

Answer from Bob M on Stack Overflow
🌐
Reddit
reddit.com › r/powershell › functions that return arrays
r/PowerShell on Reddit: Functions that return arrays
September 7, 2017 -

Even after all my experience in PowerShell, sometimes I still get a little confused by arrays.

Assume the following basic helper function (other processing is done in my script once the contents are retrieved, but it boils down to this),

function Get-Thing {
    Get-Content -Path C:\TEMP\somefile
}

It's possible that file could be non-existent, empty, contain a single line, or contain multiple lines. I want it to ALWAYS return an array, be it empty, a single item, or the array of contents. I don't seem to be able to get it to do that however, even when specifying @(Get-Content -Path C:\TEMP\somefile) or array if there are no contents or a single item. The receiving function that calls this helper function always seems to get a string instead,

function Get-Thing {
    @(Get-Content -Path C:\TEMP\somefile)
}

function Get-Thing {
    [array](Get-Content -Path C:\TEMP\somefile)
}

# results in String
$thing = Get-Thing

# results in a proper array
$thing = @(Get-Content -Path C:\TEMP\somefile)
$thing = [array](Get-Content -Path C:\TEMP\somefile)

How do I force the helper function to return an array? Or is it best practice to let it return what it will and handle the casting to an array in the receiving function? Thanks!

Top answer
1 of 4
5

When you chain cmdlets together, the PowerShell pipeline wants/needs/is designed to feed "one thing at a time" down the pipeline, e.g.

Get-Content 'somefile' | Process-TextLine
Get-ChildItem | Process-Files

It doesn't matter what you do inside the function with @() and [array], it's the connection between functions where PowerShell will undo that and treat them as individual items again.

Which is usually what you want - it means you can use the pipeline, and | foreach-object {} and foreach ($thing in ____) {}, and if you just assign the results to a variable and there were multiple results, it will be an array.

The two main reasons you might want to force an array are:

  • The case the file was empty and you're getting $null but want an empty array. This also normally works fine for pipeline and loops, but storing in a variable doesn't work. That's your @() and [array] in the outer, calling, function where you store the results. This is (AFAIK) good practice to do it like this and not try to do it from inside the function.

  • The case where you want to group things together and send (3 lines) down the pipeline all together.

e.g.

PS D:\> @(1,2,3),@(4,5,6) | foreach  { "-$_-" }
-1 2 3-
-4 5 6-

And when there is only one of those, it falls over:

@(1,2,3) | ForEach { "-$_-" }
-1-
-2-
-3-

This is the case where you need u/TalkToTheFinger's solution of putting a comma in front, and all this does is force it to be like an array inside an array:

PS D:\> @(,@(1,2,3)) | ForEach { "-$_-" }
-1 2 3-

It looks a bit weird, like you should be able to write @(@(1,2,3)) or @(@(1,2,3), ) or @($null, @(1,2,3)) but they are all not quite the same, to get it right and make it work needs one comma in front.

The above behaviour still happens - the array is unpacked and each item is sent down the pipeline, it's just that each item is now "an array of 3 items".

There are two cases here - if you want [array]$thing = get-content 'filename' to force an array even if there's only one or no lines, do it that way.

If you try to force it with the comma, it will break in the normal case of lots of lines and they will all be sent together. i.e. it works to force an array in the case of 0 or 1 result, but it breaks in the normal case of lots of results - instead of "an array of results" you have "an array of array of results". If you want to write your own get-thing and you try to force it with ,$lines what you'll get is "an array of (an array of lines)" and that will be silly.

But sometimes you do want that "several arrays together, don't flatten them" behaviour, you can force it, and they will stay together down through the pipeline.

2 of 4
2

Adding a comma in front should preserve the array even if it's empty, e.g. function Get-Thing { ,@(Get-Content -Path C:\TEMP\somefile) }

Discussions

Powershell - Pass array from one function to another
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. More on community.spiceworks.com
🌐 community.spiceworks.com
21
3
November 19, 2013
Strange Issue With Powershell Function Returning Values
Hi, I have created a function that is imported into powershell which is designed to return an array. Position 0 of array is a hash table and position 1 is an array This function works great if it is imbedded into the calling code, however, not being in… More on learn.microsoft.com
🌐 learn.microsoft.com
3
0
May 1, 2023
How to return several items from a Powershell function - Stack Overflow
In a proper programming language ... do that in Powershell. Of course, I could split this into three separate functions, but then I am back at violating the DRY rule. ... I agree with @Christian, and I add another solution. First you can return using an array explicitly or ... More on stackoverflow.com
🌐 stackoverflow.com
How can I force Powershell to return an array when a call only returns one object? - Stack Overflow
I had this problem passing an array to an Azure deployment template. If there was one object, PowerShell "converted" it to a string. In the example below, $a is returned from a function that gets VM objected according to the value of a tag. I pass the $a to the New-AzureRmResourceGroupDeployment ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Evotec
evotec.xyz › blog › powershell-returning-one-object-from-function-as-an-array
PowerShell – Returning one object from a function as an Array | Evotec Main Website Blog
March 8, 2019 - Few weeks had passed since I've initially written PowerShell – Few tricks about HashTables and Arrays I wish I knew when I started. I was happily using my tips and tricks myself till today when I noticed a strange problem. Do you know how I showed you that you could use a comma to return Array with just one member (that otherwise would be unwrapped and end up a string)? function Show-ThirdExample { param( [string[]] $Test ) [Array] $Output = foreach ($my in $Test) { $my } # I want to do something with value before returning if ($Output -is [array]) { Write-Color 'Array' -Color Green } # Actually returning , $Output }
Top answer
1 of 16
1

OK, shelf that. It’s still about scope, though. Here’s a test that worked:

function firstFunction {
    $array = 1,2,3
    return $array
}

function secondFunction {
    $array = firstFunction
    Write-Host $array
}

secondFunction

The problem was $array was defined in the firstFunction scope and you were trying to reference it in the secondFunction scope, even though you “returned” it all you really do is return the value, not the variable itself. So $array dies as soon as you exit firstFunction.

So I simply assigned the returned value to a new variable (that happened to also be called $array, but it’s not the same variable) and write it. However, if you type Write-Host $array after the secondFunction function call, you’ll get a $null!

secondFunction
Write-Host "...$array..."

Again, the $array variable dies with the function. You could Return it (Write-Output also works) and assign the original call to a variable:

$Final = secondFunction

Then everything would come out of the functions intake.

2 of 16
3

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. Below is a short example of what I’m trying to do…

function firstFunction {

$array = 1,2,3

return ,$array

}

function secondFunction {

firstFunction

Write-Host $array

}

Second function doesn’t return anything in array from the first function. Any ideas?

Hmm well I made a little test and that actually works…now why doesn’t my script work I’ve no idea…I’ll include my functions below…

function getUserLogon
{
$logonfile = "C:\Users\benw\Documents\PowershellScripts\Development\UserTracking\logon*.txt"
$logonfile2 = "C:\Users\benw\Documents\PowershellScripts\Development\UserTracking\archive\*.txt"
	$outputBox.clear()
	$username = $UserComboBox.SelectedItem.ToString()
	$startdate = $StartDateBox.text
	$enddate = $EndDateBox.text
	
	$data = @(get-content $logonfile,$logonfile2| select-string $username)
	
	$array = @()
	
	$start = [datetime]::parseexact($startdate,"MM/dd/yyyy",$null)
	$end = [datetime]::parseexact($enddate,"MM/dd/yyyy",$null)

	if($start.length -gt 0 -and $end.length -gt 0)
	{
	if($start -le $end)
	{
		foreach($line in $data)
			{
				line
				$var = [string]var = $var.substring(4,10)
				$var2 = [datetime]::parseexact($var,"MM/dd/yyyy",$null)
				if(($var2) -ge ($startdate) -and ($var2) -le ($enddate))
				{
					$array += $line
				}
			}
			if($array.length -gt 1)
			{
				$outputBox.text = $array | out-string
			}
			else
			{
				$outputBox.text = "No matches found"
			}
		}
		else
		{
			
			<#
			foreach($line in $data)
			{
				line
				$var = [string]var = $var.substring(4,10)
				$var2 = [datetime]::parseexact($var,"MM/dd/yyyy",$null)
				if(($var2) -le ($startdate) -and ($var2) -ge ($enddate)) #-ge before date -le after date -eq same date
				{
					$array += $line
				}
			}
			if($array.length -gt 1)
			{
				$outputBox.text = $array | out-string
			}
			else
			{
				$outputBox.text = "No matches found"
			}
			#>
			$outputBox.text = "Ensure the Start date is before the End date."
		}
	}
	elseif ($start.length -gt 0 -or $end.length -gt 0)
	{
		foreach($line in $data)
			{
				line
				$var = [string]var = $var.substring(4,10)
				$var2 = [datetime]::parseexact($var,"MM/dd/yyyy",$null)
				if(($var2) -eq ($startdate) -or ($var2) -eq ($enddate)) #-ge before date -le after date -eq same date
				{
					$array += $line
				}
			}
			if($array.length -gt 1)
			{
				$outputBox.text = $array | out-string
			}
			else
			{
				$outputBox.text = "No matches found"
			}
	}
	else
	{
		$outputBox.text = "Please select a Start and End Date"
	}
return ,$array
}

And my second function…

function exportCsvResults
{
	getUserLogon
	Write-Host $array
}

Which writes out nothing…

🌐
GitHub
github.com › PowerShell › PowerShell › discussions › 18601
How do cmdlets return multiple objects as an array? · PowerShell/PowerShell · Discussion #18601
PowerShell cmdlets send objects one at a time down the pipeline. This allows for pseudo multi-threading as while the first cmdlet is still outputting objects to the pipeline the second command can start working on the results. Objects that reach the end of the pipeline are returned as a single array.
Author   PowerShell
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1274507 › strange-issue-with-powershell-function-returning-v
Strange Issue With Powershell Function Returning Values - Microsoft Q&A
May 1, 2023 - In order to output your list as-is, as a single object, wrap it in an auxiliary array: function foo { $ret = [System.Collections.Generic.List[long]]::new() , $ret # construct a single-element wrapper array around the list } $k = foo $k.GetType().Name The above yields List`1, proving that the list was returned.
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
Find elsewhere
🌐
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 - What if you need to enumerate the TreeFruit array, and then enumerate the RootVegetable array later in a different function? We can try using imatch to find arrays that might contain words we know: ... This isn't very friendly code and also depends on you knowing one of the values, which defeats the whole point to begin with. We could try rebuilding the arrays by referencing the index of each object returned:
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_return
about_Return - PowerShell | Microsoft Learn
Both the informational string and the result of the calculation are returned by the function and assigned to the $a variable. If you would like to display a message within your function, beginning in PowerShell 5.0, you can use the Information stream.
🌐
Stack Overflow
stackoverflow.com › questions › 32595538 › return-an-array-from-a-function-in-powershell-3-0
Return an array from a function in PowerShell 3.0 - Stack Overflow
September 15, 2015 - $result1 = Measure-Command { $request = Invoke-WebRequest -Uri $uri} $result1.TotalMilliseconds } catch { <# If request generates exception such as 401, 404 302 etc, pull status code and add to array that will be emailed to users #> $request = $_.exception.response $time = -1 } $result += [PSCustomObject] @{ Time = Get-Date; Uri = $uri; StatusCode = [int] $request.StatusCode; StatusDescription = $request.StatusDescription; ResponseLength = $request.RawContentLength; TimeTaken = $time; } } return $result } ... Just a quick PowerShell note. You can lose the $result+= and the return statement and the function will work the same.
🌐
Pankaj Surti's Blog
pankajsurti.com › 2021 › 06 › 04 › how-to-always-return-array-object-in-powershell
How to always return array object in PowerShell? | Pankaj Surti's Blog
June 4, 2021 - Summary I have a PowerShell Script, I get all items from the SharePoint list. After getting all items I want to filter by a condition so I used the Where-Object as following. # fyi, % -> ForEach-Object [array]$items = Get-PnPListItem @HashArguments | ` %{New-Object psobject -Property ` @{ Id ...
🌐
PowerShell Test-Path
powershellfaqs.com › powershell-functions-return-values
PowerShell Functions: Return Values and Multiple Values
July 6, 2024 - In this example, the function Get-Coordinates returns an array containing the X and Y coordinates. Here is an example of a PowerShell function with parameters that returns multiple values by using a Hashtable.
🌐
GitHub
github.com › PowerShell › PowerShell › issues › 21547
I want return an empty array in a function, but it return a null value. · Issue #21547 · PowerShell/PowerShell
April 28, 2024 - Refer to Differences between Windows PowerShell 5.1 and PowerShell. I want return an empty array in a function, but it doesn't do it, which has an unintended effect.
Author   abgox
🌐
PowerShell Forums
forums.powershell.org › powershell help
Passing an array to a function - PowerShell Help - PowerShell Forums
October 16, 2023 - Then, re-assigning the $stringList = $Collection In my test example, I intentionally put down a file that I know doesn’t exit. The problem is, when the array object returns from the function, it should print out only the template name, but it is printing out other items, like the path to ...
🌐
SPGuides
spguides.com › powershell-function-array-parameters
PowerShell Function Array Parameters
January 22, 2024 - In this example, the Get-MultiplesOfTwo function returns an array containing only the elements of the $Numbers array that are multiples of two. You can see in the screenshot below, the output after I ran the code using VS code. In PowerShell, functions can accept parameters of various data types, including arrays of objects.
🌐
Tyang
blog.tyang.org › 2011 › 02 › 24 › powershell-functions-do-not-return-single-element-arrays
Powershell Functions do not return single element arrays - Managing Cloud and Datacenter by Tao Yang
February 24, 2011 - The second function boo should returns a two-element arraylist but the type of returned variable has changed from .NET arraylist to normal powershell array.
🌐
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 - The command will look for the number 6 with the array of 1,5,3,6,7,6. According to the result below, the function found two instances of the number 6 in the collection, which is correct. But what if we want the function to terminate when it finds the first instance? Then we can use the return keyword instead. Let’s add the return keyword at the beginning of line 8. This time, the PowerShell function returns the first instance and terminates.
🌐
Lieben
lieben.nu › liebensraum › 2016 › 09 › force-powershell-functions-to-array-always-and-ensure-no-zero-empty-results
Force Powershell functions to array, ALWAYS, and ensure no zero / empty results | Liebensraum
February 9, 2016 - One thing that annoys me in Powershell is it’s tendency to automatically cast arrays with 1 object to a normal object, thus you can’t do $array[0] anymore or use .Count (unless using PS v3+). You can’t really ensure your methods/functions always return a proper array, they might be empty or they might have been converted to an object.