An array is a type of data structure that stores a collection of items or objects. In PowerShell, an array can store items of different data types.
Let's look at how we can create an array in PowerShell.
We can create an array in PowerShell using @()
and providing the elements as comma-separated items. If we don't provide elements, an empty array will be created.
$arr = @(1,2,3,4,5)
We can display the array in PowerShell simply by using the variable assigned to it.
$arr
We can access individual elements of an array using their index position.
#displays first element$arr[0]
Let's take a look at an example of this.
#!/usr/bin/pwsh -Command#create an empty array$empty_arr = @()Write-Host "-------Display empty array-------"$empty_arr#create and initialize an array$num_arr = @(1,2,3,4,5)Write-Host "-------Display num array-------"$num_arr#access elements using indexWrite-Host "-------Display first element in num array-------"$num_arr[0]
In the above code snippet:
empty_arr
.num_arr
with numbers.num_arr
by just calling its variable.num_arr
using its index, that is, 0
.