Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

powershell

What is an array in PowerShell?

Gutha Vamsi Krishna

Overview

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.

Syntax

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]

Example

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 index
Write-Host "-------Display first element in num array-------"
$num_arr[0]
Example of arrays in PowerShell

Explanation

In the above code snippet:

  • In line 4, we create an empty array empty_arr.
  • In line 6, we display the empty array.
  • In line 9, we create and initialize the array num_arr with numbers.
  • In line 11, we display the array num_arr by just calling its variable.
  • In line 15, we access the first element of the array num_arr using its index, that is, 0.

RELATED TAGS

powershell
RELATED COURSES

View all Courses

Keep Exploring