SAKAR MEHRA
SAKAR MEHRA

Reputation: 3

Iterate through Hashtable containing List of values in Powershell

I am trying to print Keys and a list of values together in a single string in powershell.

I have something like this List(dict(key:value)) (key= string , value=list<String>) so my input is like this

dict(
 "apple"=$list1
 "banana"=$list2
 "orange"=$list3)
$list1=@('red','green')
$list2=@('yellow','black')
$list3=@('orange')

Now I want output something like that:

$Final_ans= apple,red_green banana,yellow_black orange,orange

How can I do this in PowerShell? I am not able to iterate like this. I tried few methods but it is giving me output System Collection.HashTable

Upvotes: 0

Views: 1500

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Assuming you have a hashtable or dictionary where all keys are strings and the value entries are arrays of strings, like this:

$list1 = @('red','green')
$list2 = @('yellow','black')
$list3 = @('orange')

$hashtable = @{
  "apple" = $list1
  "banana" = $list2
  "orange" = $list3
}

(@{} is PowerShell's native syntax for a hashtable (an unordered dictionary) literal.)

You can enumerate each key/value pair like this:

$hashtable.GetEnumerator() |ForEach-Object {
  $_.Key     # this will resolve to the key (ex. "apple")
  $_.Value   # this will resolve to the values (ex. @('red', 'green'))
}

So to construct a string like the one you describe, we can do something like this:

@($hashtable.GetEnumerator() |ForEach-Object {
  $_.Key,($_.Value -join '_') -join ','
}) -join ' '

Here, we use the -join operator to concatenate the individual strings with different delimiters:

$_.Value -join '_' turns the value pairs (ex. @('red', 'green')) into a string like red_green

$_.Key,(...) -join ',' turns the key + string we created in the previous step into a string like apple,red_green

@(...) -join ' ' then turns all of those strings into one big space-separated string apple,red_green banana,yellow_black orange,orange

Upvotes: 3

Related Questions