CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Arrays – An Introduction

PowerShell supports Arrays. PowerShell Arrays are to store collection of items. Each item in an Array is of same type or different type.

Defining Arrays in PowerShell

Arrays can be defined my assigning multiple values to the variable; and each value should be separated by a comma (“,”). Here is a simple example, to create an Array;

PS C:\> $arr = 1, 2, 3, 4, 5

If you type the variable $arr at PowerShell prompt; you can see all these elements added in the Array.

PS C:\> $arr
1
2
3
4
5

We can also define Arrays using range operator (..). The above can be written as below to define an Array with the array elements from 1 to 5.

PS C:\> $arr = 1..5

Access Array elements

Each element in an Array has an index; means Array stores these values in indexes. The starting index is “0”. That means, the first element in the Array has an index value “0”.

Positive indexes will move from “0” to high index value. We can use negative index too; “-1” is the index of the last element of the Array. Here are some examples, to access Array elements;

Access First element from the Array

PS C:\> $arr[0]
1

Access Last element from the Array

PS C:\> $arr[-1]
5

Access part of the Array

It is possible to access part of the Array, using range operator (..) combining with index operator ([]). For example, to access first 3 elements from the above array; we can write the statement, like below;

PS C:\> $arr[0..2]

This instructs to access the Array elements at the positions 0, 1 and 2.

Let’s take one more example;

PS C:\> $arr[2..-2]

So interested? Yes, as I mentioned above; we can access Array elements from the beginning and from the end of the Array. Above statement tells, to access the Array elements from the index 2 to -2; that means, the elements at the indexes 2, 1, 0, -1 and -2 are accessed.

You have to be bit cautious when using this way to access Array elements.

[..] David

PowerShell – Arrays – An Introduction

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top