PowerShell: Array, Get Items

By Xah Lee. Date: . Last updated: .

Get One Item

Write-Host (3,4,5)[2]
# 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
Write-Host (0,1,2,3,4,5,6,7)[3,6]
# 3 6

Get a Slice

array[indexBegin .. indexEnd]

Write-Host (0,1,2,3,4,5,6)[3..5]
# 3 4 5

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.

Write-Host (0,1,2,3,4)[3..1]
# 3 2 1

Write-Host (0,1,2,3,4)[3..-1]
# 3 2 1 0 4

Get Multiple Slices

# get array from index 1 to 3, and 9 to 10
Write-Host (0..20)[1..3 + 9..10]
# 1 2 3 9 10

PowerShell. Array