How to add and remove values to the Hash Table in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

You can add values to the hash table and remove values from the hash tables. To add the values to the hash table, you need to use the below format.

$hash["<key>"] = "<value>"

We have hash table already created here,

$htable = [Ordered]@{EmpName="Charlie";City="New York";EmpID="001"}


PS C:\WINDOWS\system32> $htable
Name       Value
----       -----
EmpName    Charlie
City       New York
EmpID      001

We need to add additional key “Dept” in the above hash table with the value “Technical”.

$htable['Dept']="Technical"

When you check the output of the above Hashtable, you can see the key-value is appended to the table.

PS C:\WINDOWS\system32> $htable
Name       Value
----       -----
EmpName    Charlie
City       New York
EmpID      001
Dept       Technical

You can also use the Hashtable method called Add() to add the value. The format is as below.

Add(Key, Value)

To add the same above mentioned Key-Value to the hashtable with the Add() method,

$htable.Add('Dept','Technical')

To remove the Key-value from the Hashtable, you need to use the Remove(Key) method.

For example, to remove the Key “Dept” from the hashtable,

$htable.Remove('Dept')


PS C:\WINDOWS\system32> $htable
Name       Value
----       -----
EmpName    Charlie
City       New York
EmpID      001

You cannot remove the hashtable entry with the values. You must use the key inside the Remove() method.

raja
Published on 26-Feb-2020 10:12:16
Advertisements