3

I am trying to find the index of an element from an arraylist using powershell script,however getting the below given error

Method invocation failed because [System.String[]] doesn't contain a method named 'IndexOf'.

Code Used:

[String[]]$eventList = New-Object System.Collections.ArrayList
$eventList.GetType().FullName 
$index = $eventList.IndexOf('cvv');
3
  • What is 'cvv' in this context? Commented Jan 28, 2016 at 15:53
  • Sadly, I don't think powershell arrays support IndexOf. Commented Jan 28, 2016 at 16:32
  • 'cvv' is an string that i m trying to find in $eventList which is null the thing is i want the location of 'cvv' in $eventList null it should return '-1' but it is returning error Commented Jan 29, 2016 at 6:07

1 Answer 1

1

You are casting the ArrayList to an array, just remove the cast:

$eventList = New-Object System.Collections.ArrayList

Also, you might want to consider using a List<string> instead of an ArrayList:

$eventList = New-Object System.Collections.Generic.List[string] 
Sign up to request clarification or add additional context in comments.

2 Comments

List<string> for the win! It'll also allow you to find indices based on predicates rather than string literals: $evenList.FindIndex({param($s) $s -match 'cv[u-z]'})
$s represents the item in the list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.