I looked for a while to find a simple way to create a powershell array that was more than a list; I’m talking multi-dimensional. For my own reference, here’s the easiest way I’ve found so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
## Create array ## $ArrayName= New-Object System.Data.DataTable ## Create Columns ## $col1 = New-Object System.Data.DataColumn("ID") $col2 = New-Object System.Data.DataColumn("Name") $col3 = New-Object System.Data.DataColumn("Note") ### Adding Columns for DataTable ### $ArrayName.columns.Add($col1) $ArrayName.columns.Add($col2) $ArrayName.columns.Add($col3) ## Specify row data ## $row = $ArrayName.NewRow() $row["ID"] = 1 $row["Name"] = "First" $row["Notes"] = "This is where values go." ## Add row ## $ArrayName.rows.Add($row) |
To go one step further, adding rows can be simplified by using this function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Add value to row function Add-ArrayRow { $ID = $args[0] $Name = $args[1] $Notes = $args[2] $row = $arrayName.NewRow() $row["ID"] = $ID $row["Name"] = $Name $row["Notes"] = $Notes $ArrayName.rows.Add($row) } |
To add a row with the function, just provide values in the proper order:
Add-ArrayRow "1" "ValueName" "Some other notes."
If you require to update existing values in an array, see this post on Updating Existing Powershell Array values.