Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all articles
Browse latest Browse all 3333

PowerTip: Select the Next-to-Last Item in a PowerShell Array

$
0
0

Summary:  Learn how to select the next-to-last item in a Windows PowerShell array.

Hey, Scripting Guy! Question I have a collection of objects in an array, and I need to select the next-to-last item in the array. How can this be done?

Hey, Scripting Guy! Answer Good question … Charlotte Windows PowerShell user group member Brian Wilhite says: Every now and then, there are times where I have to do just such a thing. Consider the following example:

$Objects = @(‘First’,’Second’,’Third’,’Fourth’,’Fifth’)

The example below will select the first item in the array.

$Objects[0]

If you use [-1] instead, it will select the very last item in the array. As you may have already deduced, you can use the [-2] index value to select the next-to-last item in the array, as the example below demonstrates.

 


Viewing all articles
Browse latest Browse all 3333

Trending Articles