Populate an array using dynamic variables names in Powershell

771 Views Asked by At

In this new adventure, I need to populate this matrix fast as i can. So in my mind what i need to do about the variables is:

for ($r = 0 ; $r -lt 5 ; $r++){
    new-variable r$r
    for ($i = 0 ; $i -lt 5 ; $i++){
    $rand = Get-Random -Minimum 0 -Maximum 50
    r$r += "$rand,"
    }
}

But it doesn't work, it tells me that r0 > is not a known cmdlet. This should create r0...r4 variables, wich means row0...row4 and each rn would be filled with a Random number followed by a comma.
How to do it?
And... I really don't know if I'm doing my matrices the right way, but this is what I have now:

$r1 = ""
        for ($i = 0 ; $i -lt 4 ; $i++){
        $rand = Get-Random -Minimum 0 -Maximum 50
        $r1 += "$rand,"
        }
    $r1 = $r1.Replace(" ",",")
    $r1 = $r1.TrimEnd(',')
#    Write-Host $r1

$r2 = ""
        for ($i = 0 ; $i -lt 4 ; $i++){
        $rand = Get-Random -Minimum 0 -Maximum 50
        $r2 += "$rand,"
        }
    $r2 = $r2.Replace(" ",",")
    $r2 = $r2.TrimEnd(',')
#    Write-Host $r2

$matrix = @(($r1),($r2))
foreach ($g in $matrix) {$g}
3

There are 3 best solutions below

1
On BEST ANSWER

Just because of your other question I have built this to output the random numbers in the matrix block. It uses $width and $height to define the size of $theMatrix which is built as an array of string arrays.

$width = 4
$height = 5

$theMatrix = @()
For($heightIndex = 1;$heightIndex -le $height;$heightIndex++){
    $theMatrix += ,@(1..$width | ForEach-Object{([string](Get-Random -Minimum 0 -Maximum 50)).PadLeft(2)})
}

$theMatrix | ForEach-Object{$_ -Join "|"}

This will build a matrix of random numbers. I think this is visually important to you so I converted the numbers to string so that I could use PadLeft when single digits are encountered to make the output look cleaner. In the end use $_ -Join "|" to display the matrix in its readable form. Feel free to change the delimiter to a comma or something else.

Sample Output

 1|27|23|20
29|10|25|21
31|37| 9|27
11|36|34|48
43|42|35| 9
0
On

Try it this way:

$r = 
 for ($i = 0 ; $i -lt 5 ; $i++){
  Get-Random -Minimum 0 -Maximum 50 
 }
0
On

Just for the kicks as I think Mjolinor nailed it.

This will create some dynamic variables named $r0 to $r4, and these variables will contain arrays of random integers.

for ($r = 0 ; $r -lt 5 ; $r++){
    new-variable r${r} -Value @()

    $myDynVariable = get-variable r${r}
    for ($i = 0 ; $i -lt 5 ; $i++){
        $rand = Get-Random -Minimum 0 -Maximum 50
        $myDynVariable.Value += $rand
    }
}

Some results:

$r0
24
44
23
19
32

$r1
40
12
40
28
15

$r2
41
25
19
42
5

$r3
49
43
29
15
6

$r4
32
48
22
9
4