我的建议是使用管道。一个函数产生块,另一个函数消耗它们。
使用这种方法,您不需要污染全局/脚本范围,这不是一个好主意。所需要的一切都保存在需要它的功能中。
function Get-Chunk
{
param(
[Parameter(Mandatory=$true)]$collection,
[Parameter(Mandatory=$false)]$count=10
)
#temporary array
$tmp = @()
$i = 0
foreach($c in $collection) {
$tmp += $c # add item $c to array
$i++ # increase counter; indicates that we reached chunk size
if ($i -eq $count) {
,$tmp # send the temporary array to the pipeline
$i = 0 # reset variables
$tmp = @()
}
}
if ($tmp) { # if there is something remaining, send it to the pipeline
,$tmp
}
}
function Write-ListItems
{
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]$chunk
)
process {
write-host Chunk: "$chunk"
}
}
测试功能:
$wholeList = 1..100
Get-Chunk $wholeList | Write-ListItems
Chunk: 1 2 3 4 5 6 7 8 9 10
Chunk: 11 12 13 14 15 16 17 18 19 20
Chunk: 21 22 23 24 25 26 27 28 29 30
Chunk: 31 32 33 34 35 36 37 38 39 40
Chunk: 41 42 43 44 45 46 47 48 49 50
Chunk: 51 52 53 54 55 56 57 58 59 60
Chunk: 61 62 63 64 65 66 67 68 69 70
Chunk: 71 72 73 74 75 76 77 78 79 80
Chunk: 81 82 83 84 85 86 87 88 89 90
Chunk: 91 92 93 94 95 96 97 98 99 100
Get-Chunk $wholeList 32 | Write-ListItems
Chunk: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
Chunk: 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
Chunk: 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
Chunk: 97 98 99 100
更新
我添加了一些意见,以澄清事情了。请注意,发送内容到流水线时(a)我不使用return
,因为我会从功能中跳出去。 (b)开始时的逗号将$tmp
的内容包装为数组,因此它会创建带有一个项目的新数组(这是N个项目的数组)。为什么?因为在PowerShell中有自动展开的功能,它会从数组中展开项目并将所有项目展平 - >结果将再次成为一个大数组。
例子:
function Get-Arrays {
1,2,3
"a", "b"
,(get-date)
4,5,6
}
Get-Arrays | % { "$_" }
这按预期工作:
function Get-Arrays {
,(1,2,3)
,("a", "b")
,(get-date)
,(4,5,6)
}
Get-Arrays | % { "$_" }
@JP - 感谢您的建议。这可能比我想要的复杂一点。这是一个单独使用的脚本,看起来更像是一个C#的想法。另外,在用C#编程时,我倾向于反对通过ref传递项目,因为它们打开了产生副作用的方式(一种功能性编程思想,这被认为是不可取的)。 – Mike 2011-03-28 23:34:20