Please note that we will use
ArrayList
instead ofArray
here as Array is fixed size and it can not be altered.
Using Remove()
Method
Use the Remove()
method to eliminate an item from an ArrayList in PowerShell.
1 2 3 4 5 |
[System.Collections.ArrayList]$course = "Maths", "Chemistry", "Physics" $course.Remove("Maths") $course |
1 2 3 4 |
Chemistry Physics |
In the above example, the courses titled Maths
, Chemistry
, and Physics
are added to an array list called $course
. Then, we used the Remove()
method to remove the item from an ArrayList
in PowerShell.
Why are we using ArrayList
instead of arrays in PowerShell? An array in PowerShell has a set size that cannot be altered. Therefore, we are unable to add or remove elements from an array. Instead, an ArrayList
is a good alternative to an array because it can be changed and does not have a fixed length.
We can use the Get-Type()
method and IsFixedSize
property as $course.Get-Type
and $course.IsFixedSize
to know a variable’s current data type and to check whether it has a fixed or not, respectively. If the $course.IsFixedSize
results in False
, then it means the ArrayList
does not have a fixed size and we can add/remove Items in/from it.
NOTE: The Remove()
method will remove the first instance of the supplied item.
Using RemoveAt()
Method
Use the RemoveAt()
method to get rid of an item located on a specific index in the specified ArrayList.
1 2 3 4 5 |
[System.Collections.ArrayList]$course = "Maths", "Chemistry", "Physics" $course.RemoveAt(2) $course |
1 2 3 4 |
Maths Chemistry |
The RemoveAt()
method took an index to locate an element we wanted to remove. Note that it will display an index was out of range
error if you specify an incorrect index.
Further reading:
Using RemoveRange()
Method
Use the RemoveRange()
method to remove multiple items in ArrayList.
1 2 3 4 5 6 7 |
[System.Collections.ArrayList]$days = "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" $days.RemoveRange(2,4) $days |
1 2 3 4 5 |
monday tuesday sunday |
The RemoveRange()
method took two parameters; first was the staring index, and second was the count, which means we will start removing from the index 2
and remove 4
elements from the $days
array list.
That’s all about how to remove item from Array in PowerShell.