Add Items to Array in the PowerShell

Rohan Timalsina Jan 30, 2023 Dec 23, 2021
  1. Use += to Add Items to the Array in PowerShell
  2. Use ArrayList Instead of an Array
Add Items to Array in the PowerShell

This tutorial will introduce adding items to an array in the PowerShell.

Use += to Add Items to the Array in PowerShell

An array is used to store a collection of items. The items can be the same or different types.

You can create an array and add items to it in PowerShell. We have created an array $Days as shown below.

$Days = "sunday", "monday", "tuesday"

When you add the item to an array using Array.Add(), it will display an error because the array’s length is fixed and cannot be extended.

$Days.Add("wednesday")

Output:

Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At line:1 char:1
+ $Days.Add("Wednesday")
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

You have to use += to add items to an array in the PowerShell.

$Days += "wednesday"
$Days

Output:

sunday
monday
tuesday
wednesday

Use ArrayList Instead of an Array

ArrayList does not have the length of fixed size. It can be changed and store all the data type values.

You can create an ArrayList using the command below.

$Months = New-Object System.Collections.ArrayList
$Months.IsFixedSize

Output:

False

You can add items using ArrayList.Add().

$Months.Add("Jan")
$Months.Add("Feb")
$Months.Add("Mar")
$Months

Output:

Jan
Feb
Mar
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Array