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

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

  • Comments 1
  • Likes

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.

 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • I cannot believe how easy that is, if only I googled it before trying to find it on my own ;-)