这个答案在这里:Powershell break a long array into a array of array with length of N in one line?
几乎完美地回答了我的要求。我想要做的是对我的元素进行分组,以便第一组中有一个额外的元素,而其他所有元素都在每个组中重复第一个元素。
像这样:
$bigList = ("Name","One","Two","Three","Four","Five","six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen")
$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 5
$groups = $bigList | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }
我的小组最终看起来像这样......
Name, One, Two, Three, Four, Five
Name, Six, Seven, Eight, Nine, Ten
Name, Eleven, Twelve, Thirteen
答案 0 :(得分:1)
这是怎么回事:
$bigList = ("Name","One","Two","Three","Four","Five","six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen")
$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 5
$bigList[1..$biglist.count] |
Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) } |
foreach-object {
$_.Group.Insert(0,$biglist[0])
write-output $_
}
输出:
Count Name Group
----- ---- -----
5 0 {Name, One, Two, Three...}
5 1 {Name, six, Seven, Eight...}
3 2 {Name, Eleven, Twelve, Thirteen}
这可以通过剥离第一个元素(“Name”)并通过group-object
cmdlet发送数组的其余部分来实现。通过将大列表的第一个元素中的值插入foreach-object
属性,可以在group
scriptblock中修改生成的对象。修改后的对象将重新写入管道。
假设您希望在数组列表中使用这些,您需要稍微修改代码:
$arrayList = $bigList[1..$biglist.count] |
Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) } |
ForEach-Object {
$_.Group.Insert(0,$biglist[0])
,$_.group
}
$arraylist |
% {
write-host ( $_ -join "," )
}
在这里,我们故意仅输出来自group
的{{1}}对象的groupinfo
属性。此外,我们使用group-object
运算符强制powershell输出单个数组。如果没有这样做,我们最终得到的单个数组就像,
一样,但每5个元素都有额外的'Name'实例。最后一段代码输出$biglist
的每个元素的内容,与逗号连接以证明我们确实有一个数组数组:
$arrayList