Home > Blockchain >  Powershell - comparing arrays stored in hashtable
Powershell - comparing arrays stored in hashtable

Time:09-01

I'm looking for some clean and efficient way to compare arrays stored in hashtable, without iterating over them ideally. Also without harcoding the keys

The hashtable:

Key   : somekey1
Value : {value1, value2, value3, value4}
Name  : somekey1

Key   : somekey2
Value : {value1, value2, value3}
Name  : somekey2

created with:

$hashtable = @{};

$hashtable[somekey1] = @();
$hashtable[somekey2] = @();
$hashtable[somekey3] = @();

ForEach ($key in $hashtable.keys)
{
$hashtable[$key]  = value1;
}

I would like to call something like:

Compare-Object $($hashtable.keys)[0] $($hashtable.keys)[1] -Property Value;

and the expected output would be

value4

Is this possible? (asking as a PowerShell newbie)

CodePudding user response:

Assuming each array only contains unique values, you can use the [HashSet[string]] class to calculate the difference between two sets of strings:

# Define hashtable
$hashtable = @{
  somekey1 = @('value1', 'value2', 'value3', 'value4')
  somekey2 = @('value1', 'value2', 'value3')
  somekey3 = @()
}

# Copy key collection
$keys = @($hashtable.psbase.Keys)

# Nested loops to compare each unique key pair
for($i = 0; $i -lt $keys.Count - 1; $i  ){
  for($j = $i   1; $j -lt $keys.Count; $j  ){
    # Pick next two keys to compare
    $k1,$k2 = $keys[$i,$j]

    # Calculate symmetric difference of associated arrays
    $delta = [System.Collections.Generic.HashSet[string]]::new([string[]]$hashtable[$k1])
    $delta.SymmetricExceptWith([string[]]@($hashtable[$k2]))

    # Output comparison results
    [pscustomobject]@{
        RefKey = $k1
        DiffKey = $k2
        Delta = $delta
    }
  }
}

HashSet.SymmetricExceptWith will calculate the symmetric difference between the two sets (the strings that are in one but not both), giving an output for the sample values like this:

RefKey   DiffKey  Delta
------   -------  -----
somekey1 somekey3 {value1, value2, value3, value4}
somekey1 somekey2 {value4}
somekey3 somekey2 {value1, value2, value3}
  • Related