Adrian Z.
Adrian Z.

Reputation: 934

PowerShell compare values of dictionaries

I have two dictionaries which I need to compare. The logic behind this is that if the key from the second dictionary is found between the values of the first dictionary the value from the first one needs to be replaced by what the value from the second one contains.

So in this example, the value 'MemberOf' in the FIRST dictionary should be replaced by the value of the key in the SECOND dictionary. I would like to mutate the value and not create a new dictionary/list.

The solution should be able to run in PowerShell v2.

$base_properties = `
    @{
        'user' = `
            ('CN', 'MemberOf')
    }

$expression_properties = `
    @{
        'MemberOf' = @{name='MemberOf';expression={$_.MemberOf -join ';'}}
    }

Final solution:

foreach ($prop_key in $base_properties.Keys) {
    foreach ($prop_name in $base_properties[$prop_key]) {
        if ($expression_properties.ContainsKey($prop_name)) {
            $index = $base_properties[$prop_key].IndexOf($prop_name)
            $base_properties[$prop_key][$index] = $expression_properties[$prop_name]
        }
    }
}

Upvotes: 0

Views: 1987

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174760

Simply iterate over the Keys of the first dictionary with a foreach loop and look up the value names in the second dictionary using the ContainsKey() method:

# New hashtable to hold the original and substituted expressions
$modified_properties = @{}

# iterate over the base properties
foreach($prop_key in $base_properties.Keys)
{
    # iterate over each property in the entry and assign the result to the new hashtable
    $modified_properties[$prop_key] = foreach($prop_name in $base_properties[$prop_key]){
        if($expression_properties.ContainsKey($prop_name))
        {
            # second dictionary contains an expression for the current name
            $expression_properties[$prop_name]
        }
        else
        {
            # no expression found, use original string
            $prop_name
        }
    }    
}

Upvotes: 2

Related Questions