将阵列分成多个阵列性能

时间:2019-07-15 16:04:28

标签: arrays powershell split

我尝试使用PowerShell将下面的数组拆分为多个较小的数组。但是,逐行输出文本文件需要花费大量时间。还有其他提高性能的方法吗?

原始数组($FRUITARRAY):

ORANGE,1,4,5,6,7,8
APPLE,1,3,2,4,5
ORANGE,2,4,5,6,7,8
ORANGE,3,4,5,6,7,8
APPLE,2,3,2,4,5
ORANGE,4,4,5,6,7,8
ORANGE,5,4,5,6,7,8
APPLE,3,3,2,4,5
APPLE,4,3,2,4,5

所需的输出数组:

$ORANGERRAY

ORANGE,1,4,5,6,7,8
ORANGE,2,4,5,6,7,8
ORANGE,3,4,5,6,7,8
ORANGE,4,4,5,6,7,8
ORANGE,5,4,5,6,7,8

$APPLEARRAY

APPLE,1,3,2,4,5
APPLE,2,3,2,4,5
APPLE,3,3,2,4,5
APPLE,4,3,2,4,5

代码:

$FRUITARRAY = Get-Content 'D:\work\fruit.txt'

for ($i=1; $i -lt $FRUITARRAY.Length; $i++) {
    if ($FRUITARRAY[$i].Split(',')[0].StartsWith('ORANGE')) {
        $FRUITARRAY[$i] | Out-File "D:\work\ORANGE.TXT" -Append
    }

    if ($FRUITARRAY[$i].Split(',')[0].StartsWith('APPLE')) {
        $FRUITARRAY[$i] | Out-File "D:\work\APPLE.TXT" -Append
    }
}

$ORANGEARRAY = Get-Content "D:\work\ORANGE.TXT"
$APPLEARRAY  = Get-Content "D:\work\APPLE.TXT"

1 个答案:

答案 0 :(得分:1)

可以说,最优雅的解决方案是Group-Object

$fruits = Get-Content 'D:\work\fruit.txt' | Group-Object { $_.Split(',')[0] }

$apples  = $fruits |
           Where-Object { $_.Name -eq 'apple' } |
           Select-Object -Expand Group
$oranges = $fruits |
           Where-Object { $_.Name -eq 'orange' } |
           Select-Object -Expand Group