Force Powershell function to return Array [duplicate]

你。 提交于 2021-02-08 09:56:50

问题



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?


回答1:


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.




回答2:


try this one,

function Get-AlwaysArray
{

    $returnArray = Get-ChildItem "F:\PowerShell\A"
    Write-Output $()$returnArray
}

(Get-AlwaysArray).Gettype()

IsPublic IsSerial Name                                     BaseType                                                                  
-------- -------- ----                                     --------                                                                  
True     True     Object[]                                 System.Array                                                              


来源:https://stackoverflow.com/questions/59341745/force-powershell-function-to-return-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!