How can I run compare content in a Variable against a hashtable on PowerShell

I have a hashtable as below:

$ProjectType = @{
CSharp = 'FAE04EC0-301F-11D3-BF4B-00C04F79EFBC'
Web_Application  = '349C5851-65DF-11DA-9384-00065B846F21'
Windows_Communication_Foundation = '3D9AD99F-2412-4246-B90B-4EAA41C64699'
Windows_Presentation_Foundation = '60DC8134-EBA5-43B8-BCC9-BB4BC16C2548'
Test = '3AC096D0-A1C2-E12C-1390-A8335801FDAB'
Silverlight = 'A1591282-1198-4647-A2B1-27E5FF5F6F3B'
}

I want to run the hashtable against contents in a variable $file, and get a return of the projecttype name from the hashtable if the value (guid) is found in $file.


Solution 1:

You most likely want to reverse the order of your Keys and Values on your Hash Table:

$ProjectType = @{
    'FAE04EC0-301F-11D3-BF4B-00C04F79EFBC' = 'CSharp'
    '349C5851-65DF-11DA-9384-00065B846F21' = 'Web_Application'
    '3D9AD99F-2412-4246-B90B-4EAA41C64699' = 'Windows_Communication_Foundation'
    '60DC8134-EBA5-43B8-BCC9-BB4BC16C2548' = 'Windows_Presentation_Foundation'
    '3AC096D0-A1C2-E12C-1390-A8335801FDAB' = 'Test'
    'A1591282-1198-4647-A2B1-27E5FF5F6F3B' = 'Silverlight'
}

# using this as example
$exampleFile = @'
349C5851-65DF-11DA-9384-00065B846F21
60DC8134-EBA5-43B8-BCC9-BB4BC16C2548
A1591282-1198-4647-A2B1-27E5FF5F6F3B
00000000-1198-4647-A2B1-27E5FF5F6F3B
'@ -split '\r?\n'

foreach($line in $exampleFile)
{
    if($val = $ProjectType[$line])
    {
        "$line => $val"
        continue
    }
    "$line => could not be found on reference table."
}

Solution 2:

Flip the keys and values around so that the reference GUIDs are the keys:

$ProjectType = @{
  'FAE04EC0-301F-11D3-BF4B-00C04F79EFBC' = 'CSharp'
  '349C5851-65DF-11DA-9384-00065B846F21' = 'Web_Application'
  '3D9AD99F-2412-4246-B90B-4EAA41C64699' = 'Windows_Communication_Foundation'
  '60DC8134-EBA5-43B8-BCC9-BB4BC16C2548' = 'Windows_Presentation_Foundation'
  '3AC096D0-A1C2-E12C-1390-A8335801FDAB' = 'Test'
  'A1591282-1198-4647-A2B1-27E5FF5F6F3B' = 'Silverlight'
}

Now you can easily look up any value:

$file = '3AC096D0-A1C2-E12C-1390-A8335801FDAB'

if($ProjectType.ContainsKey($file)){
  Write-Host "Found project type guid for '$($ProjectType[$file])'"
}