Add Items to Array in the PowerShell
Rohan Timalsina
Jan 30, 2023
Dec 23, 2021

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
Author: Rohan Timalsina
Related Article - PowerShell Array
- Array of Strings in PowerShell
- Create an Empty Array of Arrays in PowerShell
- Byte Array in PowerShell
- Pass an Array to a Function in PowerShell
- Sorting Array Values Using PowerShell
- Count the Length of Array in PowerShell