PowerTip: Select the Next-to-Last Item in a PowerShell Array
Summary: Learn how to select the next-to-last item in a Windows PowerShell array.
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?
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.
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.