1

I am learning about Powershell and all its many flaws. I will be passing in some parameters from the command line, and using them to make a 2-D array of that size. After reading several websites, I finally found this one which explained it clearly, but that declaration is for when you know all of the elements ahead of time and they never change.

How do I declare a 2-D array where the size is based on a variable? (just like arrayName[][]; in C)

Here's what I've got so far:

$grid[$args[1]][$args[2]]
$r=0
$c=0
$count=0

#assign a easy value to each element for testing
for($r=0; $r -lt $args[1]; $r++)
{
    for($c=0; $c -lt $args[2]; $c++)
    {
        $grid[$r][$c] = $count
        $count++
    }
}

#print out that value
Write-Output "first line: "
for($r=0; $r -lt $args[1]; $r++)
{
    for($c=0; $c -lt $args[2]; $c++)
    {
        Write-Output $grid[$r][$c]
        Write-Output " "
    }
    Write-Output "line done`nnext line: "
}
  • 1
    Linked duplicate has the answer to your question as well as better alternatives you can use in powershell. – Santiago Squarzon Jun 29 '22 at 21:52
  • No, that is not a duplicate. All those answers assume you know all of the elements ahead of time and can assign them value at the same time as the array. Here I can not. – SuperDialga Jun 30 '22 at 14:19

0 Answers0