Define an empty array:
$array = @();
Define an array with data elements in it:
$array = [array]( "foo", "bar", "baz" );
or
$array = @( "foo", "bar", "baz" );
Note: Do NOT simply use $array = "foo", "bar", "baz" because if you later edit your code and specify only one element you won't get an array object anymore, possibly introducing weird problems.
Access (read or write) an existing entry:
$element = $array[$index];
and
$array[$index] = $element;
Note: These will throw an exception if the array does not contain atleast $index+1 elements (the first entry is index 0)
Add (push) an element to the end of an array:
$array += $element;
Insert (unshift) an element at the beginning of an array:
$array = @($element) + $array;
Remove (shift) first element from an array:
$element, $array = $array;
Remove (pop) last element from an array:
[array]::Reverse($array);
$element, $array = $array;
[array]::Reverse($array);
Note: After hours of scouring the web I have found no simpler, universally working way to pop the last element from an array. Many people recommend using slices and arithmetics, but those usually break in special cases. One can only hope (albeit, most likely in vain) that Microsoft have seen fit to implement the Reverse method in an efficient way.
Get the number of entries in an array:
$count = @($array).Count;
Note: Do NOT simply use $count = $array.Count because this will break if $array contains only one object and that object happens to come with its own Count method! (And yes, I spent some time finding that bug in my script...)
List contents of an array:
$array
Loop through an array:
foreach ($element in $array) {
Write-Host $element;
}
Manually loop (C style) through an array:
for ($index=0; $index -lt $array.length ; $index++) {
Write-Host $array[$index];
}
Manually loop (C style) in reverse:
for ($index=$array.length -1 ; $index -ge 0 ; $index--) {
Write-Host $array[$index];
}