Some of the operators that work on variables also work on arrays. Let’s start with addition.
Adding Arrays
The addition operator +
concatenates – or combines – two arrays.
PS > $fibonacci = 0, 1, 1, 2, 3, 5 PS > $fib_2 = 8, 13, 21, 34 PS > $fibonacci + $fib_2 0 1 1 2 3 5 8 13 21 34
Multiplying Arrays
The multiplication operator *
copies the array a specified number of times.
PS > $fib_2 * 2 8 13 21 34 8 13 21 34
We could also use the addition +=
or multiplication *=
assignment operators to assign the resulting array back to the main array.
Containment Operators
Containment operators check whether or not an item is in an array and returns a boolean. There are four operators:
-contains
:<array> -contains <item>
-notcontains
:<array> -notcontains <item>
-in
:<item> -in <array>
-notin
:<item> -notin <array>
Let’s look at a few examples:
PS > $fibonacci -contains 4 False PS > 5 -in $fibonacci True
The -contains
and -in
operators do not differ in functionality, only the order of the operands.
-join
The -join
operator combines the items in an array into a string separated by a character or a string. Consider the following example:
PS > $fibonacci = 0, 1, 1, 2, 3, 5 PS > $fibonacci = $fibonacci -join "->" PS > $fibonacci 0->1->1->2->3->5 PS > $fibonacci.GetType().Name String
Strongly Typed Arrays
Similar to how we can force a type on a variable to create constrained variables. We can force a type onto an array so that each item has to adhere to that type. For example, if we wanted to force an array only to have strings, we can use the following notation:
PS > [String[]]$fruits = "apple", "banana", "kiwi"
Arrays of Objects
Arrays can hold objects too! Consider the following array:
$dogs_arr = @( [PSCustomObject]@{Name = 'Rufus'; Age = 10} [PSCustomObject]@{Name = 'Miku'; Age = 2} )
We utilize the multiline format of creating an array and hashtables to populate the array with dog
objects. We can then access objects individually, including their properties and methods.
PS > $dogs_arr.ForEach({ $_.Name + " is " + $_.Age + " years old."}) Rufus is 10 years old. Miku is 2 years old.
Instructions
In the spanish_nums.ps1 file, concatenate the two arrays spanish_nums_1
and spanish_nums_2
and save the resulting array to spanish_nums
.
Click Run to continue.
Check if the string seis
is in the spanish_nums
array using either the -contains
or -in
operator. Save the result to the is_seis_in_spanish_nums
variable.
Click Run to move on to continue.
Enforce the Int
type on the nums
array.
Click Run when you are done.
Use the -join
operator to combine the items of the spanish_nums
array with the ", "
separator. Save the resulting string to the spanish_nums_join_string
variable.
Click Run to continue.
Use the " >> "
separator to join the nums
array and save its result to nums_join_string
variable.
Click Run to move on.