[Powershell] How do I create and use multi-dimensional arrays in Powershell?

In PowerShell, multi-dimensional arrays can be created and used using the following steps:

  1. Declaration: Start by declaring the multi-dimensional array and specifying its dimensions. For example, to declare a 2-dimensional array with 3 rows and 4 columns, use the following syntax:
1$array = New-Object 'Object[,]' 3, 4
  1. Accessing Elements: To access or set values in the array, use the row and column indices inside square brackets. Remember that PowerShell uses zero-based indexing. For example, to set the value 10 at row 1, column 2:
1$array[1, 2] = 10
  1. Iterating through the Array: You can iterate through the multi-dimensional array using nested loops. For example, to display all the elements of the array:
1$rows = $array.GetLength(0)
2$cols = $array.GetLength(1)
3
4for ($i = 0; $i -lt $rows; $i++) {
5    for ($j = 0; $j -lt $cols; $j++) {
6        Write-Output $array[$i, $j]
7    }
8}

Here's a complete example that creates a 2-dimensional array and sets/reads values:

 1$array = New-Object 'Object[,]' 3, 4
 2
 3# Set values
 4$array[0, 0] = "A"
 5$array[0, 1] = "B"
 6$array[1, 2] = "C"
 7$array[2, 3] = "D"
 8
 9# Read values
10Write-Output $array[0, 0]  # Output: A
11Write-Output $array[0, 1]  # Output: B
12Write-Output $array[1, 2]  # Output: C
13Write-Output $array[2, 3]  # Output: D
14
15# Iterate through array
16$rows = $array.GetLength(0)
17$cols = $array.GetLength(1)
18
19for ($i = 0; $i -lt $rows; $i++) {
20    for ($j = 0; $j -lt $cols; $j++) {
21        Write-Output $array[$i, $j]
22    }
23}

This is a basic example to get you started with multi-dimensional arrays in PowerShell. Keep in mind that PowerShell supports arrays of any dimensions, and you can adapt the code as needed.