2017-08-29 130 views
2

我想根據變量將單個陣列轉換爲一組較小的陣列。所以,0,1,2,3,4,5,6,7,8,9將成爲0,1,23,4,56,7,89當大小爲3將一個PowerShell陣列切片成較小陣列組

我目前的做法:

[email protected](0,1,2,3,4,5,6,7,8,9) 
$size=3 

0..[math]::Round($ids.count/$size) | % { 

    # slice first elements 
    $x = $ids[0..($size-1)] 

    # redefine array w/ remaining values 
    $ids = $ids[$size..$ids.Length] 

    # return elements (as an array, which isn't happening) 
    $x 

} | % { "IDS: $($_ -Join ",")" } 

產地:

IDS: 0 
IDS: 1 
IDS: 2 
IDS: 3 
IDS: 4 
IDS: 5 
IDS: 6 
IDS: 7 
IDS: 8 
IDS: 9 

我想它是:

IDS: 0,1,2 
IDS: 3,4,5 
IDS: 6,7,8 
IDS: 9 

我錯過了什麼?

+0

你只是分配' $ ids'到'$ x'併發送它要用'|來迭代的流%{'。 – TheIncorrigible1

+2

使用',$ x'而不是'$ x'。 –

+0

@Bill_Stewart,解決了這個問題。如果你會以答案的形式評論你的評論,我會接受它。如果你對我想要做的事情有更優雅的解決方案,那會很有幫助。 – craig

回答

3

您可以使用,$x而不僅僅是$x

文檔中的about_Operators部分有這樣的:

, Comma operator             
    As a binary operator, the comma creates an array. As a unary 
    operator, the comma creates an array with one member. Place the 
    comma before the member. 
2
cls 
[email protected](0,1,2,3,4,5,6,7,8,9) 
$size=3 

<# 
Manual Selection: 
    $ids | Select-Object -First 3 -Skip 0 
    $ids | Select-Object -First 3 -Skip 3 
    $ids | Select-Object -First 3 -Skip 6 
    $ids | Select-Object -First 3 -Skip 9 
#> 

# Select via looping 
$idx = 0 
while ($($size * $idx) -lt $ids.Length){ 

    $group = $ids | Select-Object -First $size -skip ($size * $idx) 
    $group -join "," 
    $idx ++ 
} 
3

爲了完整起見:

function Slice-Array 
{ 

    [CmdletBinding()] 
    param (
     [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$True)] 
     [String[]]$Item, 
     [int]$Size=10 
    ) 
    BEGIN { [email protected]()} 
    PROCESS { 
     foreach ($i in $Item) { $Items += $i } 
    } 
    END { 
     0..[math]::Floor($Items.count/$Size) | ForEach-Object { 
      $x, $Items = $Items[0..($Size-1)], $Items[$Size..$Items.Length]; ,$x 
     } 
    } 
} 

用法:

@(0,1,2,3,4,5,6,7,8,9) | Slice-Array -Size 3 | ForEach-Object { "IDs: $($_ -Join ",")" }