我有一些powershell代码,可以通过SQL查询将计算机的负载返回到数组。
查询返回的成员总数有所不同。我也对数组进行了混洗。
我想获取该数组并将其按百分比分成四个或五个较小的数组。我想预先定义百分比。例如,我可能希望看到25%,25%,25%,25%。下次我想看到10%,30%,30%,40%或另外5%,35%,30%,30%。
$phasepercents = 0.1,0.2,0.2,0.25,0.25 #Percentage of machines in each
group
# AD groups to be created, Group5 is not needed as all EUC machines will be
# added in the final round
$Phase0group = @()
$Phase1group = @()
$Phase2group = @()
$Phase3group = @()
$Phase4group = @()
$computers = my sql query with returned computers
$totalmachines = $computers.count #Total No of machine in the collection
$Machinesineachgroup = @()
$phasestartnumbers = @()
# work out the percentages
$counter = 0
foreach ($phasepercent in $phasepercents)
{
$value = $phasepercent *= $totalmachines
$value = [Math]::floor($value)
$Machinesineachgroup += $value
#WriteToLog "[INFO]`t,Machines in Phase$counter is $value"
$counter +=1
}
WriteToLog "[INFO-S]`t Total Machines in each phases $Machinesineachgroup"
答案 0 :(得分:4)
这将根据$PercentageList
中的%将您的集合分成批处理大小,然后将这些批处理存储到数组数组中。您还可以修改它,以将数组存储在自定义对象的属性中,或者根据需要存储到哈希表中。 [咧嘴]
$MasterList = 1..100
$PercentageList = 10, 30, 20, 40
$Index = 0
$BatchList = foreach ($PL_Item in $PercentageList)
{
$BatchSize = [math]::Round($MasterList.Count * $PL_Item / 100, 0)
# the leading comma forces PoSh to NOT unroll the array
# instead, it is stored as whole
,$MasterList[$Index..($Index + $BatchSize - 1)]
$Index = $Index + $BatchSize
}
$BatchList[0] -join ', '
'=' * 30
$BatchList.ForEach({$_ -join ', '})
输出...
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
==============================
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, 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, 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, 97, 98, 99, 100