Array.Find on powershell array

前端 未结 5 849
耶瑟儿~
耶瑟儿~ 2021-02-13 11:28

How can I use the Array.Find method in powershell?

For example:

$a = 1,2,3,4,5
[Array]::Find($a, { args[0] -eq 3 })

gives



        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 12:06

    You need to cast the ScriptBlock as a Predicate[T]. Consider the following example:

    [Array]::Find(@(1,2,3), [Predicate[int]]{ $args[0] -eq 1 })
    # Result: 1
    

    The reason that you received the error, is because there was no matching method overload, in the case where you're passing in a PowerShell ScriptBlock. As you noted in your Get-Member output, there is no Find() method overload that accepts a ScriptBlock as its second parameter.

    [Array]::Find(@(1,2,3), { $args[0] -eq 1 })
    

    Cannot find an overload for "Find" and the argument count: "2". At line:1 char:17 + [Array]::Find(@(1,2,3), { $_ -eq 1 }) + ~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest

提交回复
热议问题