Remove Item From an Array in PowerShell

A PowerShell array is of a fixed size and cannot be changed. It means you cannot add or remove items in an array.
The best alternative is to use an ArrayList
instead of an array. An ArrayList
does not have the length of fixed size and can be modified.
This article teaches creating an ArrayList
and removing items from it in PowerShell.
Use the Remove()
Method to Remove Item From an ArrayList
in PowerShell
The following example creates an ArrayList
$days
with items Sunday
, Monday
, and Tuesday
.
[System.Collections.ArrayList]$days = "Sunday", "Monday", "Tuesday"
You can use the Get-Type()
method to view the current data type of a variable.
$days.GetType()
Output:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True ArrayList System.Object
The output shows that we have successfully created an ArrayList
. You can check whether it is a fixed size or not by running the command below.
$days.IsFixedSize
Output:
False
It returned False
, which means it does not have a fixed size.
Now, let’s add a new item, Wednesday
, to the ArrayList
$days
. The Add()
method adds a new item to the end of the ArrayList
.
$days.Add("Wednesday")
It prints the index number at which a new item is added.
3
Run the following to verify the added item in the ArrayList
.
$days
Output:
Sunday
Monday
Tuesday
Wednesday
As you can see, Wednesday
is added successfully to the ArrayList
$days
.
To remove an item from the ArrayList
, you can use the Remove()
method.
$days.Remove("Monday")
$days
Output:
Sunday
Tuesday
Wednesday
The Remove()
method removes the first occurrence of the specified item from the ArrayList
.
You can also remove a specific item by using the index number. The RemoveAt()
method allows removing an item at the specified index from the ArrayList
.
The following example removes the item at the index number 2
from the ArrayList
$days
.
$days.RemoveAt(2)
$days
Output:
Sunday
Tuesday
Sometimes you might have multiple items to remove from the specific range, e.g., 1-10, 5-9, 12-22, etc. In such cases, you can use the RemoveAt()
method to remove a range of items from the ArrayList
.
This command creates a new ArrayList
$months
.
[System.Collections.ArrayList]$months = "Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"
The following example will remove items at the index number range 6-11
from the ArrayList
$months
.
$months.RemoveRange(6,5)
Check whether those items are removed from the ArrayList
.
$months
Output:
Jan
Feb
Mar
Apr
May
Jun
Dec
If you are confused with the parameters, it uses the following syntax.
RemoveRange(index, count)
index
- starting index of the range of items to be removed.count
- number of items to remove from the starting range.