Arrays are immutable. There are three types - default, strongly typed, and ArrayList
Type: [PSObject[]]. Holds any type of data value.
$arr = @("cats", "dogs", "parrots")
Even easier, is to skip the @
sign:
$arr = ("cats", "dogs", "parrots")
Or, long-hand is to define what type of array it is:
[PSObject[]] $kitchen = 'apples', 'silverware', 18
$arr
Prints items in the array like so:
cats
dogs
parrots
Number of objects in the array - called arr
- is 3:
$arr|Measure-Object
Or, simply use .count, which is within Measure-Object:
$arr.count
$arr -contains <item to look for>
Returns a boolean.
Original array is unchanged; output is a single object, whose itmes are separated by what you tell them to be joined by.
$arr -join ", "
Prove this with:
$arr -join ", "|Measure-Object
Checks for equality, but unlike contains, will return the item if it exists.
$arr -eq "parrot"
If the object doesn't exist, it won't return a thing.
Use ne
to return the items that are not equal to what you're looking for.
My sample arrays:
$animals = ('cats', 'dogs', 'horses')
$dolphins = ('bottlenose', 'white-sided')
The second array is appended to the first.
Six objects are printed out:
$animals+$dolphins
The +=
command copies the values from the array and makes a brand new array, that includes the old and the new value(s):
Add "mice" to the animals array:
$animals+= 'mice'
Add the dolphins array to the animals array (keeps the original dolphin array but deletes and replaces the original animals array):
$animals+= $dolphins
Note that the old array is deleted.
Available for using when you only want a specific data type in the array.
For example, integers only:
[int[]] $ages = 4, 36, 47
Or, strings only:
[string[]] $flowers = "daffodil", "roses", "bleeding heart"
A collection - uses the .Net framework. May not be used as much in more complex code.
This uses the @()
function.
$shoes = @(
[pscustomobject]@{Color='blue'; Type='boots'}
[pscustomobject]@{Color='brown'; Type='heels'}
[pscustomobject]@{Color='black'; Type='neoprene booties'}
)
When you access the array of objects, with $shoes
, you get:
Color Type
----- ----
blue boots
brown heels
black neoprene booties
To access only a particular property of an object in the array, such as "heels:"
$shoes[1].Type
Update the "Type" from "heels" to "sandals:"
$shoes[1].Type = 'sandals'
Iterate through in a PowerShell friendly way:
$shoes.Type