Get Last member of array in PowerShell

This should be easy, no? I learnt a new method for getting last member of array in PowerShell last week. Up until, I used to get the count of array members, subtract 1 from it (as you know, index starts with 0) and then get that element of array:

PS C:\Users\mgoyal> $newArray = @(“one”,”two”,”three”,”four”,”five”)
PS C:\Users\mgoyal> $lastmember = $newArray[$newArray.Count – 1]
PS C:\Users\mgoyal> $lastmember
five

In place of above, we can also use this:

PS C:\Users\mgoyal> $newArray[-1]
five

Not only this, we can also get last 2nd, or 3rd element like that. The idea is that you can use negative index to get elements of array and it starts with -1 and backwards.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s