Powershell – Search Nested Hashtable

In an effort to mitigate a VMWare vCenter disaster, I was required to create a nested hashtable with up to 4 levels. Each level would contain further hashtables, or a Powershell object. The code below uses a recursive function to search through such a multi-level hashtable by flattening each root hashtable and returning true if the required data is found.

#Import data to hash
$Data = Import-Csv C:\hashTraining.csv
#Initialize the root hashtable
$f = @{}

#Populate hash using imported data and random characters for testing
$f[0] = @{0=$data[0]}
$f[0] += @{1=$data[1]}
$f += @{2="c"}
$f += @{3="d"}
$f[1] += @{0=@{3="x"}}

#Initialize search hashtable
$searchThis = @{}

#Data to find
$find = $data[1]

#Function to iterate through nested hashtable
#Will flatten nest in order to search
Function GetKeys($Hash) {

  if($Hash.GetType().name -eq "Hashtable") { #if the datapoint is a hashtable, enter it

    #Loop through the hashtable and pull out the items
    for($i=0;$i -lt $Hash.count;$I++) {

      #If the item has nested items, recurse by calling the function again
      if($Hash.Item($i)) {
        GetKeys($Hash.Item($i))
      }
    }
  }

  #Return each final item (No more nests)
  Return @{0=$hash}
}

#Loop will call the GetKeys function to return a flat hashtable to search
for($i=0;$i -lt $F.count;$i++) {

  #Populate the searchThis hashtable as a flat hashtable
  $searchThis = GetKeys($F.Item($i))

  #Loop through the flat hashtable to see if the $find datapoint is found; returns true if found
  foreach($b in $searchThis) {
    $b.ContainsValue($find)
  }
}

Leave a Reply