0

My Sample Dictionary

$testHashMap = @{
    'feature1' = @{
        'Audit'@{
          'color' = "white"
          'price' = 3
        }
        'Space'  = 2
        'Usage' = 3
    }
    'feature2' = @{
        'Audit'@{
          'color' = "black"
          'price' = 3
        }
        'Space'  = 5
        'Usage' = 3
    }
}
  • How can I access directly "color" key's value?
  • When I prompt a key it will be search related key and return its value

Expected Output:

Please enter a property: "color"
Color: white in feature1
Color: black in feature2

I want to doing it with recursive, how can I achieve this purpose?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Ichigo Kurosaki
  • 135
  • 1
  • 6
  • 2
    This is not json or powershell. – js2010 May 28 '23 at 16:35
  • 1
    Please show in code what you have tried so far. If you don't know how to start, try do it without recursion first. Research how to iterate over the keys and values of a hashtable (hint: `GetEnumerator()` method). After that, try to add recursion. – zett42 May 28 '23 at 16:50

1 Answers1

0

The custom Get-LeafProperty function from this answer can handle arbitrary object graphs as inputs, including nested hashtables (dictionaries), as in your question.

It reports the leaf properties / dictionary entries as name-path/value pairs; e.g., for your first color entry, it returns the following custom object (expressed as a literal here):
[pscustomobject] @{ NamePath = 'feature1.Audit.color'; Value = 'white' }

You can therefore combine this function with Where-Object and ForEach-Object to filter the output by the leaf keys of interest:

$keyName = 'color'

# The key of the leaf entries of interest.
$keyName = 'color'

@{  # sample input hashtable from you question; streamlined and syntax-corrected
  feature1 = @{
    Audit = @{
      color = 'white'
      price = 3
    }
    Space = 2
    Usage = 3
  }
  feature2 = @{
    Audit = @{
      color = 'black'
      price = 3
    }
    Space = 5
    Usage = 3
  }
} | 
  Get-LeafProperty | 
  Where-Object { ($_.NamePath -split '\.')[-1] -eq $keyName } |
  ForEach-Object {
    "${keyName}: $($_.Value) in $(($_.NamePath -split '\.')[0])"
  }

Output:

color: white in feature1
color: black in feature2
mklement0
  • 382,024
  • 64
  • 607
  • 775