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

Fla*_*eel 2 arrays powershell multidimensional-array

我在 Powershell 中有一组自定义对象。每个对象都有一个可以在数组中查找的唯一引用和一个我希望稍后使用的值,该值不一定是唯一的。该数组填充在 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
}
Run Code Online (Sandbox Code Playgroud)

构建数组后,我想以某种方式访问与正确objRef对应的objValue。我知道您可以使用-contains参数测试数组是否包含一个值,但我不知道如何使用该值获取对象的索引。

基本上这个数组就像一个查找表。我想要一个函数来放入 objRef 以获取 objValue。

在这种情况下 objValue 是一个System.Management.Automation.PSCredential,为了安全起见,每个对象的密码都是在运行时输入的。在工作中,我有时必须使用相同的 5 个凭据在不同的机器上安装相同的软件 30 次,弄清楚这一点将帮助我远程自动化该过程。

提前致谢!

Jer*_*ert 5

PowerShell 是基于 .NET 的,所以 .NET 中的数组可以做的所有事情,它们都可以在 PowerShell 中做。特别是,因为他们实现了IList,他们有.IndexOf方法@(10, 4, 6).indexof(6)返回2

当然,在您的特定情况下,哈希表更合适,因为在搜索数组时查找值有恒定的时间需要线性时间。这在小数组的情况下无关紧要,但如果您在循环中做事,则加起来很快。