December 18th, 2012

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

Doctor Scripto
Scripter

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.

 

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.

Feedback