![](/img/trans.png)
[英]How can I find last index in array with method findIndex() in proper interval? JS
[英]How can I find the index of a String array element using the [Array]::FindIndex method in PowerShell?
另一个PowerShell noob问题。
我有一个包含企业名称的字符串数组,并且我正在编写一个脚本,该脚本遍历目录的文件夹并将文件夹名称与数组中包含的名称进行比较。 找到匹配项时,我需要获取找到匹配项的数组索引。 我已经使用以下代码成功完成了针对完全匹配的操作:
foreach($file in Get-ChildItem $targetDirectory)
{
if($businesses -like "$file*")
{
$myIndex = [array]::IndexOf($businesses, [string]$file)
}
}
我之所以使用-like "$file*"
的原因是,有时企业名称使用“ LLC”或“ INC”或类似名称,在我们为文件夹命名时有时不包括(反之亦然)。 我想修改我的$myIndex
行以找到这些索引。
我正在尝试使用
$myIndex = [array]::FindIndex($Merchant, {args[0] -like "$file*"})
但是我得到了错误
找不到“ FindIndex”和参数计数:“ 2”的重载。
我尝试使用[Predicate[string]]{args[0] -like "$file*"}
强制转换第二个参数,但是得到相同的结果。 我已经阅读了该方法的文档,但是我的基本问题之一是我不了解System.Predicate类型。 我什至不确定我是否编写正确; 我发现了一个类似的示例,但改用了[int]
。 也许我正在解决所有错误,但是我感觉自己已经接近,无法在任何地方找到谜题中缺失的部分。
在此先感谢您的帮助。
[Array]::FindIndex($Merchant, [Predicate[string]]{})
仅在$Merchant
类型为string[]
:
$Merchant
是一个字符串数组,可以工作:
PS C:\> $Merchant = 1,2,3 -as [string[]]
PS C:\> [array]::FindIndex($Merchant,[Predicate[String]]{param($s)$s -eq "3"})
2
$Merchant
是Int32
的数组,不起作用:
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
强制转换为Predicate[int]
时工作正常:
PS C:\> [array]::FindIndex($Merchant,[Predicate[int]]{param($s)$s -eq 3})
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.