Resize array

Welcome Forums General PowerShell Q&A Resize array

This topic contains 3 replies, has 2 voices, and was last updated by

1 year, 7 months ago.

  • Author
  • #72250

    Points: 1
    Rank: Member

    Hi there
    I had the same problem long time ago and I cant remember what I did to solve it:(
    basically I have an array of lets say 100 users(numbers might change, this is just for testing) which I need to "divide" to X number of "groups" and I want to then add each group members to a group for example(could be some other task).
    so I import my big list:
    $numbers= import-csv C:\files\out.csv
    I the use this function to resize based on whatever size I want in this case 2 since I want 2 in each of the 50 groups:
    function Resize-Array ([object[]]$InputObject, [int]$SplitSize = 100)
    $length = $InputObject.Length
    for ($Index = 0; $Index -lt $length; $Index += $SplitSize)
    , ($InputObject[$index .. ($index + $splitSize – 1)])
    $resizedarray=Resize-Array -InputObject $numbers -SplitSize 50
    shows 50
    now I want to cycle inside the $rezisedarray(which has 50 "groups") and inside every "group" to add each of the members of that "group" to the ad group
    but that doesn't seem to work, so I tried write-host to see if I can even show these members and it doesn't show them:
    $resizedarray[0] |%{write-host $_.displayname}

    and that shows the users just fine.

    any ideas?

  • #72253

    Points: 1
    Rank: Member

    managed to solve the first problem
    I was just referencing the wrong item
    I should have used:
    foreach($s in $resizedarray)
    foreach ($i in $s){ Write-Host $i -ForegroundColor Green $group }
    foreach ($i in $s){ Write-Host $i.displayname -ForegroundColor Green $group }

    now I'm trying to combine it all including the 50 groups I have(adding each 2 mebers of the sub array($I) into a group of its own
    like this:

    foreach($s in $resizedarray) {
    $Group="Group{0:0}" -f $Groupid
    foreach ($i in $s){ Write-Host $i -ForegroundColor Green $group }

    but what I'm getting is:
    user1 group220
    user2 group220
    user3 group221
    user4 group221

    for some reason it starts counting the group at 220 instead of at 1 like group1,group2,group3

    any ideas why?

  • #72265

    Points: 0
    Rank: Member

    My guess is that you are using PowerShell's ISE and the variable $groupid has been set by the first run of the script and incremented every time the script runs. Since it's ISE the variable does not get cleared at the end of each run. It stays active in the active environment.

    You could test running in a console powershell or just adding something like $groupid=0 before the foreach loop to initialize it back to 0.

    • #72298

      Points: 1
      Rank: Member

      you are absolutely right my friend

The topic ‘Resize array’ is closed to new replies.