简体   繁体   English

如何使用Powershell通过值查找数组中元素的索引

[英]How to find the index of an element in an array by its value using Powershell

I have an array of custom objects in Powershell. 我在Powershell中有一组自定义对象。 Each object has a unique reference with which it can be looked up in the array and a value I wish to use later which is not necessarily unique. 每个对象都有一个唯一的引用,可以在数组中查找该引用,还有一个我以后希望使用的值,它不一定是唯一的。 The array is populated in a for loop as below 如下所示,该数组填充在for循环中

#Create empty array
$array1 = @()

#Populate array
foreach($otherElement in $otherArray){
  #Create custom array element
  $arrayElement = New-Object PSObject

  #Update Credential element   
  $arrayElement | Add-Member -type NoteProperty -Name 'objRef' -Value $($otherElement.getAttribute("ref") )
  $arrayElement | Add-Member -type NoteProperty -Name 'objValue' -Value $($otherElement.getAttribute("someValue") )

  #Add element to array
  $array1 += $arrayElement
}

After building the array I want to get access to the objValue corresponding to the correct objRef in some way. 构建数组后,我想以某种方式访问​​与正确的objRef对应的objValue I know that you can test if an array contains a value using the -contains parameter but I don't know how to get the index of the object with that value. 我知道您可以使用-contains参数测试数组是否包含值,但是我不知道如何使用该值获取对象的索引。

Basically this array is acting like a look up table. 基本上,此数组的作用类似于查找表。 I want a function to put in an objRef to get out an objValue. 我想要一个函数放入objRef以获得objValue。

The objValue in this case is a System.Management.Automation.PSCredential , the password for each object is input at runtime for security. 在这种情况下,objValue是System.Management.Automation.PSCredential ,为安全起见,在运行时输入每个对象的密码。 At work I have to sometimes install the same software 30 odd times on different machines with the same 5 credentials and figuring this out will help me automate the process reomtely. 在工作中,有时我必须在具有相同5个凭据的不同机器上安装30次相同的软件,而弄清这一点将帮助我彻底地自动化该过程。

Thanks in advance! 提前致谢!

PowerShell is .NET based, so everything arrays in .NET can do , they can do in PowerShell. PowerShell是基于.NET的,因此.NET中的所有数组都可以执行 ,它们可以在PowerShell中执行。 In particular, since they implement IList , they have the .IndexOf method : @(10, 4, 6).indexof(6) returns 2 . 特别地,由于它们实现了IList ,因此它们具有.IndexOf方法@(10, 4, 6).indexof(6)返回2

Of course, in your particular case a hash table is more appropriate, since looking up values there is constant time while searching through an array takes linear time. 当然,在您的特定情况下,哈希表更合适,因为查找值的时间恒定,而在数组中搜索则需要线性时间。 This matters little in the case of small arrays, but adds up quickly if you're doing things in a loop. 对于小数组而言,这无关紧要,但是如果您是循环执行的话,这很快就会加起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM