Initialize dictionary at declaration using PowerShell

43,979

Solution 1

No. The initialization syntax for Dictionary<TKey,TValue> is C# syntax candy. Powershell has its own initializer syntax support for System.Collections.HashTable (@{}):

$drivers = @{"nitrous"="vx"; "directx"="vd"; "openGL"="vo"};

For [probably] nearly all cases it will work just as well as Dictionary<TKey,TValue>. If you really need Dictionary<TKey,TValue> for some reason, you could make a function that takes a HashTable and iterates through the keys and values to add them to a new Dictionary<TKey,TValue>.


The C# initializer syntax isn't exactly "direct" anyway. The compiler generates calls to Add() from it.

Solution 2

For those who like to really use Dictionary. In my case I had to use another c# dll which has a dictionary as parameter:

New-Object System.Collections.Generic.Dictionary"[String,String]"

This was probably not possible back in 2011

Share:
43,979
C.J.
Author by

C.J.

Updated on July 13, 2022

Comments

  • C.J.
    C.J. almost 2 years

    Given this powershell code:

    $drivers = New-Object 'System.Collections.Generic.Dictionary[String,String]'
    $drivers.Add("nitrous","vx")
    $drivers.Add("directx","vd")
    $drivers.Add("openGL","vo")
    

    Is it possible to initialize this dictionary directly without having to call the Add method. Like .NET allows you to do?

    Something like this?

    $foo = New-Object 'System.Collections.Generic.Dictionary[String,String]'{{"a","Alley"},{"b" "bat"}}
    

    [not sure what type of syntax this would involve]

  • C.J.
    C.J. almost 13 years
    I don't really need dictionary. A .NET hash table will work just fine.
  • Bacon Bits
    Bacon Bits over 6 years
    It's worth noting that a HashTable and a Dictionary do have differences, but that those differences will largely be considered not relevant for common PowerShell scripting.