Saturday, March 23, 2013

Multi Dimantional Arrays Framework Style

I know the standard Powershell array creation looks like this: $myArray = @(), but I wanted something more. Something with some teeth.

One Dimensional Array:
$myarray = [Array]::CreateInstance([String], 10)

Two Dimensional Array:
$myarray = [Array]::CreateInstance([Object], 10, 10)

Three Dimensional Array:
$myarray = [Array]::CreateInstance([Boolean], 10, 10, 10)

Not sure why anyone would want to create a 10 x 3 matrix but I wanted to show that the type of object you want to use goes first. followed by the amount of dimensions and their 1 based amount.

One based?

Yep. Try doing 10. 9 is the limit minus 1 for 0 equals 10

$UserNames = [Array]::CreateInstance([String], 3)
$UserNames[0] = "First User"
$UserNames[1] = "Second User"
$UserNames[2] = "Third User"

An additioanl advantage here is that you can use GetLength

for($c=0;$c -lt $UserNames.GetLength(0);$c++)

write-host $UserNames.GetValue($c)

No comments:

Post a Comment