Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 287
D. Foley Avatar asked Apr 03 '17 06:04

D. Foley


People also ask

How do you add values to a hash table?

Add(Object, Object) Method is used to adds an element with the specified key and value into the Hashtable. Syntax: public virtual void Add(object key, object value);

How do I add values to a Hashtable in PowerShell?

And, you can add keys and values to a hash table by using the addition operator ( + ) to add a hash table to an existing hash table. For example, the following statement adds a "Time" key with a value of "Now" to the hash table in the $hash variable. You can also add values that are stored in variables.

How do I iterate through a Hashtable in PowerShell?

In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.

What is GetEnumerator in PowerShell?

GetEnumerator in PowerShell is used to iterate through the Hashtable or array to read data in the collection. GetEnumerator doesn't modify the collection data. Use foreach or foreach-object in PowerShell to iterate over the data read from the GetEnumerator.


1 Answers

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
like image 122
Martin Brandl Avatar answered Sep 23 '22 01:09

Martin Brandl