2011-05-14 138 views
4

我有一個包含7個項目的對象。Powershell - 分批循環通過對象3

$obj.gettype().name 
Object[] 

$obj.length 
7 

我穿過的3批我不想使用模函數要循環,其實我是想能夠創建一個新的對象只從該批次的3個項目。僞代碼:

$j=0 
$k=1 
for($i=0;$i<$obj.length;$i+=3){ 
    $j=$i+2 
    $myTmpObj = $obj[$i-$j] # create tmpObj which contains items 1-3, then items 4-6, then 7 etc 
    echo "Batch $k 
    foreach($item in $myTmpObj){ 
     echo $item 
    } 
    $k++ 
} 

Batch 1 
item 1 
item 2 
item 3 

Batch 2 
item 4 
item 5 
item 6 

Batch 3 
Item 7 

問候, 特德

回答

7

你的僞代碼幾乎是真實的。我剛纔已經改變了它的語法和使用範圍運算符(..):

# demo input (btw, also uses ..) 
$obj = 1..7 

$k = 1 
for($i = 0; $i -lt $obj.Length; $i += 3) { 

    # end index 
    $j = $i + 2 
    if ($j -ge $obj.Length) { 
     $j = $obj.Length - 1 
    } 

    # create tmpObj which contains items 1-3, then items 4-6, then 7 etc 
    $myTmpObj = $obj[$i..$j] 

    # show batches 
    "Batch $k" 
    foreach($item in $myTmpObj) { 
     $item 
    } 
    $k++ 
} 

輸出看上去完全是必需的。

+0

甜的,範圍操作員正是我所尋找的,歡呼羅馬。 – ted 2011-05-14 06:23:17

+1

它看起來像檢查'if($ j -ge $ obj.Length)...'(索引超出範圍)在PowerShell中甚至不需要。 – 2011-05-15 06:12:01

0

看看是否需要爲這一個可以工作(我假設你項n,$obj元素)

 
$obj | % {$i=0;$j=0;[email protected]{}} 

if($i!=3 and $batches["Batch $j"]) { $batches["Batch $j"]+=$_; $i+=1 } 
else {$i=1;$j+=1;$batches["Batch $j"][email protected]($_)} 

} {$batches} 

應與鍵如"Batch 1""Batch 2"返回一個哈希表($batches).. 。每個鍵與三個項目的數組相關。