add string element in arraylist , 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 method named 'add'. @ c:\users\administrator\desktop\qwedqwe.ps1:9 char:15 + $eventlist.add <<<< ("hello") + categoryinfo : invalidoperation: (add:string) [], runtimeexception + fullyqualifiederrorid : methodnotfound
as mentioned in comments, if you've developing in ise (or ide) , assigned $eventlist type cast, so:
[string[]]$eventlist = @() or similar, commenting out previous lines won't - variable exists , have type bound remainder of lifetime.
you can remove previous assignments remove-variable eventlist
once you've got sorted, can move on locating index. if you're interested in index of exact match, use indexof():
ps> $eventlist.indexof('hi') 2 if isn't flexible enough, use a generic list<t>, implements findindex().
findindex() takes predicate - function returns $true or $false based on input (the items in 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 call findindex() $predicate function argument:
ps> $eventlist.findindex($predicate) 0 (it matches hello @ index 0 because starts h)
Comments
Post a Comment