PowerShell – Remove Item from Array

Remove Item from Array in PowerShell

Please note that we will use ArrayList instead of Array 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.

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.

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.

Using RemoveRange() Method

Use the RemoveRange() method to remove multiple items in ArrayList.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *