jdebr
jdebr

Reputation: 537

How can I find the index of a String array element using the [Array]::FindIndex method in PowerShell?

another PowerShell noob question.

I have an array of strings that contains the names of businesses and I am writing a script that iterates through the folders of a directory and compares the folder names to the names contained in the array. When I find a match I need to get the array index where the match was found. I've done this successfully for exact matches using the following code:

foreach($file in Get-ChildItem $targetDirectory)
{
    if($businesses -like "$file*")
    {
        $myIndex = [array]::IndexOf($businesses, [string]$file)
    }
}

The reason I use -like "$file*" is because sometimes the name of the business has "LLC" or "INC" or something like that, which occasionally wasn't included when we named the folders(and vice versa). I would like to modify my $myIndex line to find these indexes as well.

I'm trying to use

 $myIndex = [array]::FindIndex($Merchant, {args[0] -like "$file*"})

But I'm getting the error

Cannot find an overload for "FindIndex" and the argument count: "2".

I've tried casting the second argument using [Predicate[string]]{args[0] -like "$file*"} but get the same result. I've read the documentation for the method but one of my basic problems is I don't understand the System.Predicate type. I'm not even sure if I'm writing it properly; I found an example that was similar but used [int] instead. Maybe I'm going about it all wrong but I feel like I'm close and just can't find the missing piece of the puzzle anywhere.

Thanks in advance for any help.

Upvotes: 1

Views: 4535

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

[Array]::FindIndex($Merchant, [Predicate[string]]{}) only works if $Merchant is of type string[]:

$Merchant is a string array, works:

PS C:\> $Merchant = 1,2,3 -as [string[]]
PS C:\> [array]::FindIndex($Merchant,[Predicate[String]]{param($s)$s -eq "3"})
2

$Merchant is an array of Int32s, doesn't work:

PS C:\> $Merchant = 1,2,3 -as [int[]]
PS C:\> [array]::FindIndex($Merchant,[Predicate[String]]{param($s)$s -eq "3"})
Cannot find an overload for "FindIndex" and the argument count: "2".
At line:1 char:1
+ [array]::FindIndex($Merchant,[Predicate[String]]{param($s)$s -eq "3"})
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Works fine when cast to Predicate[int]:

PS C:\> [array]::FindIndex($Merchant,[Predicate[int]]{param($s)$s -eq 3})
2

Upvotes: 5

Related Questions