Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two hashtables to make one

I have two hash tables and I need to compare them. Let me explain my problem :

[hashtable]$User = @{
"Jack" = "AdminLA, AdminUSA";
"John" = "AdminAustralia";
"Sarah" = "AdminIceland";
"Arnold" = "AdminUSA";
"Maurice" = "AdminAustralia, AdminCanada";
}


[hashtable]$Profil = @{
"AdminLA" = "P1";
"AdminIceland" = "P2";
"AdminUSA" = "P3";
"AdminCanada" = "P4";
"AdminAustralia" = "P5" ;
"AdminCroatia" = "P6";
}

I want to have this kind of result :

Key         Value
---         -----
Jack        P1, P3
John        P5
Sarah       P2
Arnold      P3
Maurice       P5, P4

Actually, I have only one value (I haven't succeeded to have multiple values. For example Jack must have P1 and P3 and I have only P1).

How can I fix it?

I have already tried:

$User.GetEnumerator() | select Key, @{n='Value'; e={$Profil[$_.Value]}}

and

$User.GetEnumerator() | %{[PSCustomObject]@{aKey=$_.Key;bValue=$Profil[$_.Value]}}

Any idea?

like image 430
P0werSh3ell Avatar asked Jul 26 '18 13:07

P0werSh3ell


People also ask

How do I merge Hashtables in powershell?

Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.

Do Hashtables allow duplicates?

Hashtable Features It does not accept duplicate keys. It stores key-value pairs in hash table data structure which internally maintains an array of list.

When should you not use Hashtables?

There are some operations which are not efficiently supported by hash tables, such as iterating over all the elements whose keys are within a certain range, finding the element with the largest key or smallest key, and so on.

Are Hashtables efficient?

The most memory efficient datastructure for associations The hash table with the best memory efficiency is simply the one with the highest load factor, (it can even exceed 100% memory efficiency by using key compression with compact hashing ). A hash table like that does still provide O(1) lookups, just very slow.


1 Answers

Use this expression

$User.GetEnumerator() | Select-Object Key, @{name='Value'; expression={($_.Value -split ", " | Foreach-Object {$Profil[$_]}) -join ", "}}

This basically creates an array of input values, get the values from $Profil for each element and then creates a string from these values.

like image 96
Robert Dyjas Avatar answered Sep 29 '22 06:09

Robert Dyjas