Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Example code to show how to create , add , insert and manipulate dictionary data structure in Powershell.
- ChatGPT DALL-E Bot:
- # Creating a dictionary in PowerShell
- $dictionary = @{}
- # Adding key-value pairs to the dictionary
- $dictionary.Add("Name", "John")
- $dictionary.Add("Age", 30)
- $dictionary.Add("City", "New York")
- # Accessing values from the dictionary
- Write-Host "Name: " $dictionary["Name"]
- Write-Host "Age: " $dictionary["Age"]
- Write-Host "City: " $dictionary["City"]
- # Updating values in the dictionary
- $dictionary["Age"] = 35
- Write-Host "Updated Age: " $dictionary["Age"]
- # Removing a key-value pair from the dictionary
- $dictionary.Remove("City")
- Write-Host "Dictionary after removing City key: "
- foreach ($key in $dictionary.Keys) {
- Write-Host "$key : $($dictionary[$key])"
- }
- # Inserting a key-value pair at a specific index in the dictionary
- $newDictionary = @{}
- $newDictionary.Add("Country", "USA")
- $newDictionary.Add("State", "California")
- foreach ($key in $newDictionary.Keys) {
- $index = 1 # Insert at index 1
- $tempDict = @{}
- foreach ($k in $dictionary.Keys) {
- if ($k -eq $index) {
- $tempDict.Add($key, $newDictionary[$key])
- }
- $tempDict.Add($k, $dictionary[$k])
- $index++
- }
- if ($index -eq ($dictionary.Count + 1)) {
- # Insert at end of dictionary
- $tempDict.Add($key, $newDictionary[$key])
- }
- # Update original dictionary with new key-value pair(s)
- $dictionary = $tempDict
- }
- Write-Host "Updated Dictionary after inserting new key-value pairs: "
- foreach ($key in $dictionary.Keys) {
- Write-Host "$key : $($dictionary[$key])"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement