Add the value of a variable to a HashTable as the key

D. Foley picture D. Foley · Apr 3, 2017 · Viewed 9.1k times · Source

PowerShell V5 Windows 10

For example, the variable $EmployeeID contains the string testValue, and I want to simply use the value of the previous variable inside the $HastTable.Add() function. It would look like this:

$HashTable.Add($EmployeeID, 'some_value')

Except of course that does not work, but hopefully I am clear in what I want to achieve.

With that, I can then access the value like I normally do:

$var = $HashTable.testValue

Answer

Martin Brandl picture Martin Brandl · Apr 3, 2017

You are doing it right and should be able to access the key wihtout any issues (you only don't get auto completion this way):

$HashTable = @{ }
$EmployeeID = "testValue"
$HashTable.Add($EmployeeID, 'some_value')
$var = $HashTable.testValue
$var

Output:

some_value