Search code examples
functionpowershelltypesreturn

Force Powershell function to return Array



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?


Solution

  • 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.