DarkLite1 DarkLite1 - 3 months ago 47
PowerShell Question

PowerShell Remove item [0] from an array

I'm struggling a bit to remove the first line (item ID) of an array.

$test.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array


To list all the options I tried
,$test | gm
and it clearly states:

Remove Method void IList.Remove(System.Object value)
RemoveAt Method void IList.RemoveAt(int index)


So when I try
$test.RemoveAt(0)
I get the error:

Exception calling "RemoveAt" with "1" argument(s): "Collection was of a fixed size."At line:1 char:1
+ $test.RemoveAt(1)
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException


So I finally found here that my array needs to be of the type
System.Object
to be able to use
$test.RemoveAt(0)
. Is it best practice to declare all the arrays in the beginning of the script as a list? Or is it better to convert the arrays with
$collection = ({$test}.Invoke())
to a list later on when this functionality is needed?

What are the pro's and cons of both types? Thank you for your help.

Answer

Arrays are fixed-size, like the error says. RemoveAt() is an inherited method that doesn't apply to normal arrays. To remove the first entry in the array, you could overwrite the array by a copy that includes every item except the first, like this:

$arr = 1..5

$arr
1
2
3
4
5

$arr = $arr[1..($arr.Length-1)]

$arr
2
3
4
5

If you need to remove values at different indexes then you should consider using a List. It supports Add(), Remove() and RemoveAt():

#If you only have a specific type of objects, like int, string etc. then you should edit `[System.Object] to [System.String], [int] etc.
$list = [System.Collections.Generic.List[System.Object]](1..5)

$list
1
2
3
4
5

$list.RemoveAt(0)

$list
2
3
4
5

See my earlier SO answer and about_Arrays for more details about how arrays work.

Comments