This PowerShell blog post will show how to create and use arrays in PowerShell.
Arrays allow us to store data in a very structural way and access them during runtime. An array can contain almost any type of data (int, string, etc.). Arrays allow us to store multiple values inside a single variable.
Create an Array
To create an array with PowerShell, we use the following code:
$myarray = @(1, 2, 3, 4, 5)
We can also create an array using the following code:
$fruits = "apple", "banana", "cherry"
Access Array Elements
To access the elements of an array, we use the following code (remember that the array index starts at 0)
$fruits[0] # Returns apple
Modify Array Elements
To modify an array element, we use the following code.
$fruits[1] = "blueberry"
Adding and Removing Elements
To add elements to an array, we use the following code
$fruits += “kiwi”
Iterating over Array
To iterate over each element of an array, we can use a for-each loop
foreach ($fruit in $fruits) {
Write-Host $fruit
}
To check the length of an array, we use $fruits.length, and to sort an array, we use $sortedFruits = $fruits | Sort-Object
To join all the elements of an array, we use $fruitString = $fruits -join ‘, ‘
Leave a Reply