Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Powershell function to return Array [duplicate]


How can i force a Powershell function to return an Array?
This simple function for Example, if "C:\New folder" contains only 1 element, it will not return an Array.

function Get-AlwaysArray
{
    $returnArray = gci "C:\New folder"
    Write-Output $returnArray
}
(Get-AlwaysArray).Gettype()

There is already a Thread with a pretty good upvoted answer here But non of the answer works unfortunally.
Here is what i have tried:

function Get-AlwaysArray {
    [Array]$returnArray = gci "C:\New folder"
    Write-Output $returnArray   
}
(Get-AlwaysArray).Gettype()

function Get-AlwaysArray {
    $returnArray = @(gci "C:\New folder")
    Write-Output @($returnArray)   
}
(Get-AlwaysArray).Gettype()

function Get-AlwaysArray {
    $returnArray = @(gci "C:\New folder")
    Write-Output @($returnArray | Where-Object {$_})   
}
(Get-AlwaysArray).Gettype()

function Get-AlwaysArray {
    [Object[]]$returnArray = @(gci "C:\New folder")
    Write-Output @($returnArray | Where-Object {$_})   
}
(Get-AlwaysArray).Gettype()

The only way it would work is

function Get-AlwaysArray {
    $returnArray = gci "C:\New folder"
    Write-Output $returnArray 
}
@(Get-AlwaysArray).Gettype()

But i dont want to add this, everytime i call my function.
What am i doing wrong?

like image 257
Evilcat Avatar asked Mar 19 '26 06:03

Evilcat


1 Answers

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.

like image 177
Bob M Avatar answered Mar 22 '26 00:03

Bob M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!