Coding Ref

Dictionaries in PowerShell

Dictionaries in PowerShell

In PowerShell, a dictionary is a collection of key-value pairs that can be used to store and manage data. You can create a dictionary by using the New-Object cmdlet and specifying the System.Collections.Generic.Dictionary type.

Here's an example:

$dict = New-Object System.Collections.Generic.Dictionary

This will create an empty dictionary called $dict. You can then add key-value pairs to the dictionary using the Add() method.

Here's an example:

$dict = New-Object System.Collections.Generic.Dictionary
$dict.Add("Key1", "Value1")
$dict.Add("Key2", "Value2")

In this example, two key-value pairs are added to the dictionary: Key1 is mapped to Value1, and Key2 is mapped to Value2.

You can access the value of a key in a dictionary by using the Item property and specifying the key. Here's an example:

$dict = New-Object System.Collections.Generic.Dictionary``
$dict.Add("Key1", "Value1")
$dict.Add("Key2", "Value2")
Write-Output $dict.Item("Key1")

In this example, the value of the key Key1 is accessed by using the Item property and the Write-Output cmdlet is used to print it to the console. The code will output Value1.

You can also use a foreach loop to iterate over the key-value pairs in a dictionary and access their values.

Here's an example:

$dict = New-Object System.Collections.Generic.Dictionary``
$dict.Add("Key1", "Value1")
$dict.Add("Key2", "Value2")
foreach ($key in $dict.Keys) {
Write-Output "Key: $key, Value: $($dict.Item($key))"
}

In this example, a foreach loop is used to iterate over the keys in the dictionary using the Keys property. For each key, the code uses the Item property to access the corresponding value and outputs it to the console. The code will output the following:

Key: Key1, Value: Value1
Key: Key2, Value: Value2

Conclusion

Dictionaries are a useful data structure in PowerShell for storing and managing data in key-value pairs.

You'll also like

Related tutorials curated for you

    How to append content to a file in PowerShell

    How to declare global variables in PowerShell

    How to ping in PowerShell

    How to join a domain in PowerShell

    How to pause in PowerShell

    Get the full path of ChildItem in PowerShell

    String formatting in PowerShell

    What is read-host in PowerShell?

    How to sort in PowerShell

    How to use String Contains in PowerShell

    What is Echo in PowerShell?

    How to rename a file in PowerShell