Powershell Multidimensional Arrays

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

I have a way of doing Arrays in other languagues like this:

$x = "David" $arr = @()  $arr[$x]["TSHIRTS"]["SIZE"] = "M" 

This generates an error.

回答1:

You are trying to create an associative array (hash). Try out the following sequence of commands

$arr=@{} $arr["david"] = @{} $arr["david"]["TSHIRTS"] = @{}     $arr["david"]["TSHIRTS"]["SIZE"] ="M" $arr.david.tshirts.size 

Note the difference between hashes and arrays

$a = @{} # hash $a = @() # array 

Arrays can only have non-negative integers as indexes



回答2:

from powershell.com:

PowerShell supports two types of multi-dimensional arrays: jagged arrays and true multidimensional arrays.

Jagged arrays are normal PowerShell arrays that store arrays as elements. This is very cost-effective storage because dimensions can be of different size:

$array1 = 1,2,(1,2,3),3 $array1[0] $array1[1] $array1[2] $array1[2][0] $array1[2][1] 

True multi-dimensional arrays always resemble a square matrix. To create such an array, you will need to access .NET. The next line creates a two-dimensional array with 10 and 20 elements resembling a 10x20 matrix:

$array2 = New-Object 'object[,]' 10,20 $array2[4,8] = 'Hello' $array2[9,16] = 'Test' $array2 

for a 3-dimensioanl array 10*20*10

$array3 = New-Object 'object[,,]' 10,20,10 


回答3:

To extend on what, manojlds, said above is that you can nest Hashtables. It may not be a true multi-dimensional array but give you some ideas about how to structure the data. An example:

$hash = @{}  $computers | %{     $hash.Add(($_.Name),(@{         "Status" = ($_.Status)         "Date"   = ($_.Date)     })) } 

What's cool about this is that you can reference things like:

($hash."Name1").Status 

Also, it is far faster than array's for finding stuff. I use this to compare data rather than use matching in Arrays.

$hash.ContainsKey("Name1") 

Hope some of that helps!

-Adam



回答4:

Knowing that PowerShell pipes objects between cmdlets, it is more common to use an array of PSCustomObjects:

$arr = @(     New-Object PSObject -Property @{Name = "David";  Article = "TShirt"; Size = "M"}     New-Object PSObject -Property @{Name = "Eduard"; Article = "Trouwsers"; Size = "S"} ) 

Or for PowerShell Version 3 and above:

$arr = @(     [PSCustomObject]@{Name = "David";  Article = "TShirt"; Size = "M"}     [PSCustomObject]@{Name = "Eduard"; Article = "Trouwsers"; Size = "S"} ) 

And grep your selection like:

$arr | Where {$_.Name -eq "David" -and $_.Article -eq "TShirt"} | Select Size 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!