Thursday, January 30, 2014

PowerShell Quickie - Array navigation

Of course we all know that reading from a simple array is performed by specifying the element number(s), so if we look at the following example:

$array = "apple", "banana", "orange", "plum"

The first element in the array is '0' so:

Write-Host $array[0]
apple

The third element, therefore is '2' so:

Write-Host $array[2]
orange

Very easy, but a lesser known trick is to count from the last element backwards. The last element of an array is '-1' and so forth...

Write-Host $array[-1]
plum

Write-Host $array[-2]
orange

This is useful, without this you would have to do something like this:

Write-Host $array[$array.length - 1]
plum

Write-Host $array[$array.length - 2]
orange

Cheers!




No comments:

Post a Comment