powershell - PowerShell 中的数组展开

标签 powershell

我试图理解 Posh 中的数组展开,但以下内容让我感到困惑。在这个例子中,我返回包裹在另一个数组中的数组(使用逗号),这基本上在外部数组在返回时展开后给我原始数组。为什么当我通过对结果的变量使用数组运算符 (@) 间接包装结果时得到正确的结果(只是数组),但如果我直接在函数上使用 @ 则得到数组中的数组? @ operator 是否对其参数的不同类型表现不同? @运算符和数组展开有PS帮助文章吗?

function Unroll
{
    return ,@(1,2,3)
}

Write-Host "No wrapper"
$noWrapper = Unroll #This is array[3]
$noWrapper | % { $_.GetType() }

Write-Host "`nWrapped separately"
$arrayWrapper = @($noWrapper) #No change, still array[3]
$arrayWrapper | % { $_.GetType() }

Write-Host "`nWrapped directly"
$directArrayWrapper = @(Unroll) #Why is this array[1][3] then?
$directArrayWrapper | % { $_.GetType() }
Write-Host "`nThe original array in elem 0"
$directArrayWrapper[0] | % { $_.GetType() }

谢谢

最佳答案

如果您从 Unroll 函数中删除逗号运算符,它的行为将如您所愿。

function Unroll
{
    return @(1,2,3)
} 

在这种情况下,$arrayWrapper = @($noWrapper)$directArrayWrapper = @(Unroll) 相同。

您可以使用 this SO question 找到有关数组展开的更多信息在这个article about array literals In PowerShell

关于powershell - PowerShell 中的数组展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070014/

相关文章:

windows - 根据大小将文本文件拆分为更小的文件 (Windows)

function - 如何成功运行 2 个不同的 Powershell 脚本

string - 从 PowerShell 中的路径字符串中提取最后一个组件

powershell - 如何在powershell中查找当前脚本的位置/路径

powershell - 在批处理脚本中执行 powershell 命令时转义字符

powershell - PowerShell 新对象声明中 '+' 的含义

datetime - PS 将 Get-WinEvent 与 FilterXPath 和日期时间变量一起使用?

powershell - 如何将 InputObject 上的 NoteProperties 访问到远程处理 session

excel - Powershell - Excel 将列的格式更改为文本

Powershell 4.0 无法从 psm1 导入哈希表