1

I was using powershell Arraylist to hold the list generated by splitting a string. When i try to remove the first item in the list using the below code the enitre list is going null.

[System.Collections.ArrayList]$teststringlist=New-Object System.Collections.ArrayList
$teststring ="Test1,Test2,Test3"
$teststringlist = $teststring.Split(",")
$teststringlist=$teststringlist.RemoveAt(0)

How i can remove the first item at Index 0 of the Arraylist in powershell

MindSwipe
  • 7,193
  • 24
  • 47
mystack
  • 4,910
  • 10
  • 44
  • 75

2 Answers2

4

RemoveAt doesn’t return a value (see https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist.removeat?view=netcore-3.1) so instead of

$teststringlist=$teststringlist.RemoveAt(0)

just do this:

$teststringlist.RemoveAt(0)
mclayton
  • 8,025
  • 2
  • 21
  • 26
1

You can do this using the Select-Object cmdlet and the -Skip parameter:

$teststringlist = $teststringlist | Select-Object -Skip 1

Alternative you can do it like this:

$teststringlist[1 .. ($a.teststringlist)]
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • Select-Object -Skip 1 always skips the first one?.Do you have any idea why RemoveAt is not working.I was using Arralist because ArrayList isn’t fixed, you can remove elements from them using the Remove() method – mystack Aug 11 '20 at 08:44
  • 1
    it also works but the it doesn't return anything so when you reassign it with the return method, it is empty. And yes, -skip 1 always skips the first one – Martin Brandl Aug 11 '20 at 08:46