PowerShell Remove item [0] from an array
An alternative option is to use Powershell's ability to assign multiple variables (see this other answer).
$arr = 1..5
$first, $rest= $arr
$rest
2
3
4
5
It's been a feature of Powershell for over a decade. I found this functionality from an MSDN blog post:
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.