BennKingy
BennKingy

Reputation: 1583

Match key to value between 2 hash tables - Powershell

Apologies I am not clued up with PowerShell just yet.

I have two hash tables, one containing the label name and the ID. The other contains a folder path and the label name.

I am trying to extract the label ID e.g 'e58e1e18-da7e-493c-9961-a7deff6dc7f7' to use in a for each statement.

I am looping through the folder's hash table, and need to be able to match the folder key with the label value, if there is a match, extract that value from the labels hash.

Example: 'C:\OTD\Cat' would have the id of 'e58e1e18-da7e-493c-9961-a7deff6dc7f7' as Label1 matches in both hash tables.

$labels = @{
    'Label1' = 'e58e1e18-da7e-493c-9961-a7deff6dc7f7'
    'Label2' = '6514c00d-001e-4041-9207-f31aebc5e13a'
    'Label3' = 'e58e1e18-da7e-493c-9961-a7deff6dc7f7'
}

$folders = @{
    'C:\OTD\Cat' = 'Label1' 
    'C:\OTD\Dog' =  'Label2'
    'C:\OTD\Frog' = 'Label3'
}

# Match key/value in a hashtable and return the labels id value
$folders.GetEnumerator() | ForEach-Object{
    If($_.value = matches key name in labels hash, grab that label ID to use here)
}

Thank you for looking at my question!

Upvotes: 0

Views: 843

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174525

Use the corresponding values as index keys for the second hashtable:

$folders.Keys | % {
  # Grab the label
  $folderLabel = $folders[$_]

  # Use label as key to resolve label ID
  $labelId = $labels[$folderLabel]
} 

You can nest these as crazily as you want (although it might hurt readability of your code):

$labelIDs = $folders.Keys | % {
  $labels[$folders[$_]]
}

As a side note, I recommend iterating through dictionaries as lists of key-value pairs by explicitly calling GetEnumerator() instead of iterating over Keys:

$folders.GetEnumerator() |%{
  $folderPath = $_.Key
  $folderLabel = $_.Value
  $labelID = $labels[$_.Value]
}

Upvotes: 1

Related Questions