强制Powershell函数返回Array [英] Force Powershell function to return Array

查看:57
本文介绍了强制Powershell函数返回Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


如何强制Powershell函数返回数组?
这个简单的函数示例,如果"C:\ New folder"仅包含1个元素,则不会返回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()

唯一可行的方法是

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?

推荐答案

首先,使用数组子表达式运算符@(...).此运算符将一个或多个语句的结果作为数组返回.如果只有一项,则数组只有一个成员.

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" )

在开关 -NoEnumerate 中使用 Write-Output 来防止PowerShell展开阵列.

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

Write-Output -NoEnumerate $returnArray

通过使用以下语法,您也可以使用 Write-Output 有效地获得相同的结果,而无需使用 -NoEnumerate .

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

Write-Output ,$returnArray

$ returnArray 前面的逗号有效地创建了一个以 $ returnArray 作为其唯一元素的新数组.然后,PowerShell展开此新的单元素数组,将完整的原始 $ 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.

这篇关于强制Powershell函数返回Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆