Reputation: 628
I have an array of custom objects in 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
#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. 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.
Basically this array is acting like a look up table. I want a function to put in an objRef to get out an objValue.
The objValue in this case is a System.Management.Automation.PSCredential, the password for each object is input at runtime for security. 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.
Thanks in advance!
Upvotes: 4
Views: 14806
Reputation: 28779
PowerShell is .NET based, so everything arrays in .NET can do, they can do in PowerShell. In particular, since they implement IList
, they have the .IndexOf
method: @(10, 4, 6).indexof(6)
returns 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.
Upvotes: 8