February 18th, 2016

PowerTip: Count backwards in array

Doctor Scripto
Scripter

Summary: Cloud & Datacenter Management MVP, Thomas Rayner, shows how to count backwards in a Windows PowerShell array.

Hey, Scripting Guy! Question I know I can access the first, second, and third items in an array by using $Array[0], $Array[1], and $Array[2], but how can I count backwards?

Hey, Scripting Guy! Answer Use negative numbers, for example:

$Array = @(‘first’,’second’,’third’)

$Array[0]

$Array[1]

$Array[2]

$Array[-1]

$Array[-2]

$Array[-3]

This will output the following:

first

second

third

third

second

first

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.