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.
Remove() Method to Remove Item From an
ArrayList in PowerShell
The following example creates an
$days with items
[System.Collections.ArrayList]$days = "Sunday", "Monday", "Tuesday"
You can use the
Get-Type() method to view the current data type of a variable.
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.
False, which means it does not have a fixed size.
Now, let’s add a new item,
Wednesday, to the
Add() method adds a new item to the end of the
It prints the index number at which a new item is added.
Run the following to verify the added item in the
Sunday Monday Tuesday Wednesday
As you can see,
Wednesday is added successfully to the
To remove an item from the
ArrayList, you can use the
Sunday Tuesday Wednesday
Remove() method removes the first occurrence of the specified item from the
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
The following example removes the item at the index number
2 from the
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
This command creates a new
[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
Check whether those items are removed from the
Jan Feb Mar Apr May Jun Dec
If you are confused with the parameters, it uses the following syntax.
index- starting index of the range of items to be removed.
count- number of items to remove from the starting range.