【问题标题】:How can I find the index of a String array element using the [Array]::FindIndex method in PowerShell?如何在 PowerShell 中使用 [Array]::FindIndex 方法查找字符串数组元素的索引?
【发布时间】:2015-08-20 21:47:41
【问题描述】:

另一个 PowerShell 菜鸟问题。

我有一个包含企业名称的字符串数组,我正在编写一个脚本,它遍历目录的文件夹并将文件夹名称与数组中包含的名称进行比较。当我找到匹配项时,我需要获取找到匹配项的数组索引。我已经使用以下代码成功完成了完全匹配:

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]。也许我做错了,但我觉得我已经很接近了,只是无法在任何地方找到缺失的拼图。

提前感谢您的帮助。

【问题讨论】:

    标签: arrays powershell


    【解决方案1】:

    [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
    

    $MerchantInt32s 的数组,不起作用:

    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
    

    【讨论】:

    • 好的,这就是我认为它会起作用的方式,谢谢您的澄清。但是,即使我尝试您的示例,我仍然会遇到相同的错误。我可以使用错误的版本吗?我很确定我有 2.0 版
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2019-08-06
    • 2021-04-16
    • 1970-01-01
    相关资源
    最近更新 更多