Array.Find on powershell array

前端 未结 5 858
耶瑟儿~
耶瑟儿~ 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 11:56

    Trevor Sullivan's answer is the right one, not only for Find() static method, but for FindIndex() as well.

    When you've got several NIC cards with both ipv4 & ipv6 active on your servers and want to check the ipv4 IP/netmask pairs, something like this is good :

    $NetworkAdapters = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled = True' | Select-Object -Property Description, IPAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder, DNSDomain
    $NetworkAdapters | % {
      "Adapter {0} :" -f $_.Description
      # array'ing to avoid failure against single homed netcards
      $idx = [System.Array]::FindIndex(@($_.IPAddress), [Predicate[string]]{ $args[0] -match "\d+.\d+.\d+.\d+" })
      "  IP {0} has netmask {1}" -f @($_.IPAddress[$idx]), @($_.IPSubnet)[$idx]
    }
    

    My point is it works like a charm on 2012 WinPE, and fails on a production Win7 wks. Anyone got an idea ?

提交回复
热议问题