Advertisement
wetyukmnbxc

Untitled

Mar 27th, 2023
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. Example code to show how to create , add , insert and manipulate dictionary data structure in Powershell.
  3.  
  4. ChatGPT DALL-E Bot:
  5. # Creating a dictionary in PowerShell
  6. $dictionary = @{}
  7.  
  8. # Adding key-value pairs to the dictionary
  9. $dictionary.Add("Name", "John")
  10. $dictionary.Add("Age", 30)
  11. $dictionary.Add("City", "New York")
  12.  
  13. # Accessing values from the dictionary
  14. Write-Host "Name: " $dictionary["Name"]
  15. Write-Host "Age: " $dictionary["Age"]
  16. Write-Host "City: " $dictionary["City"]
  17.  
  18. # Updating values in the dictionary
  19. $dictionary["Age"] = 35
  20. Write-Host "Updated Age: " $dictionary["Age"]
  21.  
  22. # Removing a key-value pair from the dictionary
  23. $dictionary.Remove("City")
  24. Write-Host "Dictionary after removing City key: "
  25. foreach ($key in $dictionary.Keys) {
  26.     Write-Host "$key : $($dictionary[$key])"
  27. }
  28.  
  29. # Inserting a key-value pair at a specific index in the dictionary
  30. $newDictionary = @{}
  31. $newDictionary.Add("Country", "USA")
  32. $newDictionary.Add("State", "California")
  33.  
  34. foreach ($key in $newDictionary.Keys) {
  35.     $index = 1 # Insert at index 1
  36.     $tempDict = @{}
  37.     foreach ($k in $dictionary.Keys) {
  38.         if ($k -eq $index) {
  39.             $tempDict.Add($key, $newDictionary[$key])
  40.         }
  41.         $tempDict.Add($k, $dictionary[$k])
  42.         $index++
  43.     }
  44.     if ($index -eq ($dictionary.Count + 1)) {
  45.         # Insert at end of dictionary
  46.         $tempDict.Add($key, $newDictionary[$key])
  47.     }
  48.     # Update original dictionary with new key-value pair(s)
  49.     $dictionary = $tempDict
  50. }
  51.  
  52. Write-Host "Updated Dictionary after inserting new key-value pairs: "
  53. foreach ($key in $dictionary.Keys) {
  54.     Write-Host "$key : $($dictionary[$key])"
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement