I've got a script which indexes information from our equipment. To store and analyze the information I've created a class:
Add-Type @'
public class CPObject
{
public int id;
public string name;
public string displayname;
public string classname;
public string ip;
public string netmask;
public string ManagementServer;
}
'@
Then when I run the script I've been planning to go through the object class to translate name to IP with the following function:
Function NameToIP {
Param([int]$id=0, [string]$name="")
$CPObject = $CPNetworkObjects | Where-Object { $_.id -eq $id -and $_.name -eq $name }
If($CPObject.count -eq 1){
$CPObject.ip
} else {
""
}
}
It works, but it's terribly slow as the $CPNetworkObjects contains over 12 000 elements of the type CPObject.
I want to speed this up. Is there any way to index an array to make the search more efficient or is the only solution to try to lessen the number of objects used?
Kind regards, Patrik
If any give combination of id plus name is unique, you can speed up a name-to-ip resolution by building a lookup table:
$NameToIP = @{}
Foreach ($Object in $Array) { $NameToIP["$($Object.id)_$($Object.Name)"] = $Object.ip }
Function NameToIP {
Param([int]$id=0, [string]$name="")
$NameToIP["$id_$name"]
}