How to create a Dictionary in PowerShell?


To create a dictionary in the PowerShell we need to use the class Dictionary from the .Net namespace System.Collections.Generic. It has TKey and TValue. Its basic syntax is

Dictionary<TKey,TValue>

To learn more about this .Net namespace check the link below.

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0

To create a dictionary we will first create the object for the dictionary object class with the datatypes. In the below example, we need to add the Country name and the country code. So we need String and Int.

$countrydata = New-Object System.Collections.Generic.Dictionary"[String,Int]"

Once we check the type of the $countrydata variable, it should be the dictionary. For example,

Example

PS C:\> $Countrydata.GetType() | ft -AutoSize

Output

IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     Dictionary`2 System.Object

Let’s check which methods are available.

Example

PS C:\> $Countrydata | Get-Member -MemberType Method | Select Name, Membertype

Output

Name              MemberType
----              ----------
Add                   Method
Clear                 Method
Contains              Method
ContainsKey           Method
ContainsValue         Method
CopyTo                Method
EnsureCapacity        Method
Equals                Method
GetEnumerator         Method
GetHashCode           Method
GetObjectData         Method
GetType               Method
OnDeserialization     Method
Remove                Method
ToString              Method
TrimExcess            Method
TryAdd                Method
TryGetValue           Method

So we can use Add() method to insert the members.

Example

PS C:\> $Countrydata.Add("India",91)
PS C:\> $Countrydata.Add("Algeria",213)

Once you check the value, its output should be in the Key-Value pair.

Example

PS C:\> $Countrydata

Output

Key     Value
---     -----
India      91
Algeria   213

Generally, PowerShell programmers don’t use the directory because of its uncommon syntax and tend to use the Hashtable because can be easily created.

Updated on: 15-Dec-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements