Search code examples
powershellpowerpointpowershell-remoting

Need to add and find element index value in arraylist in powershell?


add string element in arraylist and find it's index value?

[code...]
$eventList = New-Object System.Collections.ArrayList
$eventList.Add("Hello")
$eventList.Add("test")
$eventList.Add("hi")

Not working throwing error:-

Method invocation failed because [System.String[]] doesn't contain a method named 'Add'.
At C:\Users\Administrator\Desktop\qwedqwe.ps1:9 char:15
+ $eventList.Add <<<< ("Hello")
    + CategoryInfo          : InvalidOperation: (Add:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Solution

  • As mentioned in the comments, if you've developing this in ISE (or another IDE) and previously assigned $eventList with a type cast, like so:

    [string[]]$eventList = @()
    

    or similar, commenting out previous lines won't help you - the variable already exists and will have that type bound to it for the remainder of its lifetime.

    You can remove any previous assignments with Remove-Variable eventList


    Once you've got that sorted, we can move on to actually locating the index. If you're interested in the index of an exact match, use IndexOf():

    PS> $eventList.IndexOf('hi')
    2
    

    If that isn't flexible enough, use the a generic List<T>, which implements FindIndex().

    FindIndex() takes a predicate - a function that returns $true or $false based on input (the items in the list):

    $eventList = New-Object System.Collections.Generic.List[string]
    $eventList.Add("Hello")
    $eventList.Add("test")
    $eventList.Add("hi")
    $predicate = {
      param([string]$s) 
    
      return $s -like 'h*'
    }
    

    And then call FindIndex() with the $predicate function as the only argument:

    PS> $eventList.FindIndex($predicate)
    0
    

    (it matches Hello at index 0 because it starts with an h)