Pages

Tuesday, June 9, 2009

Working with Arrays and Hash Tables in PowerShell

PowerShell variables can also store arrays. Each item is assigned a unique Index number and starts with 0.

To create an array in PowerShell, create a variable and assign list of values separated by comma.

PS H:\> $MyArray = ('A','B','C','D','E','F','G','H')

To display the values just use square brackets along with the Array Index.

PS H:\> $MyArray[0]
A


You can simply type the PowerShell Variable names to display all the values in that array.

PS H:\> $MyArray
A
B
C
D
E
F
G
H


To Get the length of the array just use the Count Property of the Array.

PS H:\> $MyArray.Length
8


Updating Array

You can also change any element in array by using the Index.
PS H:\> $MyArray[4] = "VIJAY"
PS H:\> $MyArray
A
B
C
D
VIJAY
F
G
H

Adding new element to Existing Array

You can’t add new element to the existing array. You need to create new array and using + operator you can add new elements to existing array.

PS H:\> $MyNewArray = ('KADIYALA','KRISHNA')
PS H:\> $MyArray = $MyArray+$MyNewArray
PS H:\> $MyArray
A
B
C
D
VIJAY
F
G
H
KADIYALA
KRISHNA

You can also specify the range of the integers to create an array. You just have to specify ranges of integers using the .. operator

PS H:\> $MyArray = 1..10
PS H:\> $MyArray
1
2
3
4
5
6
7
8
9
10

Creating Multi Dimensional Arrays
Creating multi dimensional array is very similar to creating single dimensional arrays. You need to enclose the values in “(“and “)”.

PS H:\> $MyMultiArray = (('A','B'),('C','D'),('E','F'))
PS H:\> $MyMultiArray
A
B
C
D
E
F
PS H:\> $MyMultiArray[0]
A
B
PS H:\> $MyMultiArray[0][0]
A
PS H:\> $MyMultiArray[1][0]
C

Creating Hash Tables

Hash tables are very similar to multi dimensional arrays. The major difference between Multi dimensional and Hash tables are the Index. In Hash tables you can use your own index name to read the values.

PS H:\> $MyHash = @{'First_Name'='Vijaya'; 'Middle_Name'='Krishna'; 'Last_Name'='Kadiyala'}
PS H:\> $myHash['First_Name']
Vijaya
PS H:\> $myHash['Middle_Name']
Krishna
PS H:\> $myHash['Last_Name']
Kadiyala
PS H:\> $myHash['First_Name'] + ' ' + $myHash['Middle_Name'] + ' ' + $myHash['Last_Name']
Vijaya Krishna Kadiyala
PS H:\>

No comments: