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
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);
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With