PowerShell: Array
Array is a list of values. the values can be the same type or different types.
Create Array (the comma operator)
it can be created by values separated by comma
$x = 3, 4, 5
items can be different types:
$x = 3, "abc", 5
can be multiple lines:
$x = "a", "b", "c"; $x.foreach({ echo $_ })
WARNING: Last item must not have comma. And best to add a SEMICOLON at the end. This is a frequent error if you write PowerShell script.
Create a Array of Single Item
To create a array of single item, precede the item by a comma.
$a = ,4
or use the Array Sub-Expression Operator @(...) (Collection to Array)
$x = @(4)
Create Array by Array Sub-Expression Operator
Create Array by Range Operator
min..max
-
(the range operator.)
Creates an array of contiguous integers, from
min..max, inclusive.
$a = 3..7 # result 3 4 5 6 7
length
use method
length
or its alias
count
(3,4,5).length -eq 3
get items
get one item
- Array index start at 0.
- Negative index count from right.
$x = 3,4,5 $x[2] -eq 5
get a multiple items
# get index 3 and 6 (0,1,2,3,4,5,6,7)[3,6] # (3,6)
Get a slice
$x = 0,1,2,3,4,5,6,7 $x[3..6] # result is 3,4,5,6
Get multiple slices
use + inside [] between slices, to get different items.
$x = 0..99 # get array from index 1 to 10 and 30 to 40 $x[1..10 + 30..40]
set item
$x = 1, 2, 3 $x[0] = "b" $x # b 2 3
or use method SetValues(val, index)
$x = 1, 2, 3 $x.SetValue("b",0) $x
Append an Item
Use operator +=
to add a item to end of array.
Note, the array data structure is optimized for not changing size. It has to recreate the array and is slow. The more items in a array, the slower it is to change size.
$x = 1, 2, 3 # add a item "b" to the end $x += "b" $x
delete item
It's not easy to delete array item in PowerShell.
Array data structure is not designed to change size.
Instead of delete, just replace the value with $null
.
join arrays
use +
operator.
$a = 1,2 $b = 3,4,5 $a+$b
delete array
assign the whole to $null
$a = 1,2,3 $a = $null $a
Iterate Over Array
reset all items
array.Clear()
Sets all item values to the default value of the array's item type.
$aa = 1, 2, 3 $aa.Clear()
filter array
Array to String
# array to string [string] @(1, 2, 3) -eq "1 2 3"
# make sure last string ends semicolon, not comma $x= @( "abc", "def", "ghi" ) ($x -join ";") -eq "abc;def;ghi"