Saturday, March 3, 2018

Any sequence of numbers can index a PowerShell array

It's moderately common to take a "slice" of PowerShell arrays by using a range inside the brackets, like $arr[0..3] to get a sequence of the first four elements. The .. syntax isn't special-cased in array indexing; you can use any expression that generates a series of numbers. Even pipelines are fine. If it's complicated, you might have to enclose the whole thing in parentheses. To get all the array elements at even indexes, you could do this:

$arr[(0..($arr.Length - 1) | ? { $_ % 2 -eq 0 })]

No comments:

Post a Comment