Hashtable Manipulation: Adding Key-Value Pairs in PowerShell

Powershell @ Freshers.in

Hashtables are versatile data structures in PowerShell, allowing you to store key-value pairs efficiently. Knowing how to add key-value pairs to a hashtable is essential for effective script development. In this article, we’ll explore various methods to add key-value pairs to hashtables in PowerShell, along with practical examples and outputs.

Adding Key-Value Pairs Using Traditional Syntax

The traditional syntax for creating a hashtable in PowerShell involves using the @{} notation. You can add key-value pairs to a hashtable during initialization or by directly assigning values to keys.

Example 1: Adding Key-Value Pairs During Initialization

$hashTable = @{
    "Name" = "John"
    "Age" = 30


Name Value
---- -----
Name John
Age  30

Example 2: Adding Key-Value Pairs by Direct Assignment

$hashTable = @{}
$hashTable["City"] = "New York"
$hashTable["Country"] = "USA"


Name                           Value
----                           -----
City                           New York
Country                        USA

Using the Add Method

Another method to add key-value pairs to a hashtable is by using the Add method. This method provides a cleaner and more explicit way to add elements to a hashtable.

Example 3: Adding Key-Value Pairs Using the Add Method

$hashTable = @{}
$hashTable.Add("Language", "PowerShell")
$hashTable.Add("Version", "7.2")


Name                           Value
----                           -----
Language                       PowerShell
Version                        7.2

In PowerShell, adding key-value pairs to a hashtable is a fundamental operation for managing and manipulating data efficiently. By mastering the techniques demonstrated in this article, you can enhance your scripting skills and streamline your PowerShell workflows.

Author: user