PowerShell: Array, Get Items

By Xah Lee. Date: . Last updated: .

Get One Item

$x = 3,4,5
$x[2] -eq 5

Out-of-Bound Index

Out-of-Bound Index return $null

# get out-of-bound index 9
$x = (0,1,2,3)[9]
$null -eq $x
# True

Get Multiple Items

# get index 3 and 6
(0,1,2,3,4,5,6,7)[3,6]
# (3,6)

Get a Slice

array[indexBegin .. indexEnd]

$x = 0,1,2,3,4,5,6,7
$x[3..6]
# result is 3,4,5,6

If indexBegin is greater than indexEnd, the slice is taken in reverse order, possibly wrapping over the end if there are negative numbers in index.

$x = 0,1,2,3,4
$x[3..1]
# return 3 2 1

$x = 0,1,2,3,4
$x[3..-1]
# return 3 2 1 0 4

Get Multiple Slices

$x = 0..99

# get array from index 1 to 10 and 30 to 40
$x[1..10 + 30..40]

PowerShell: Array