Eskimo
Eskimo

Reputation: 35

How to Convert a C# Dictionary in the code to a Powershell object?

Can any one help me? I have C# code that builds a dictionary and I need to convert that dictionary into PowerShell object. The object will then be pass it to a PowerShell script.

My Dictionary

Dictionary<string, Dictionary<string, string>>

Upvotes: 1

Views: 675

Answers (1)

Keith Hill
Keith Hill

Reputation: 201932

Current versions (v3/v4) should be able to use the Dictionary directly but I don't remember how well v2 handled generics. Anyway, here is some pseudo-code (not guaranteed to compile) to convert to a hashtable of hashtables:

var hashtable = new Hashtable();
foreach (var kvPair in dict) {
    var hashtableInner = new Hashtable();
    foreach (var kvPairInner in kvPair.Value) {
        hashtableInner.Add(kvPairInner.Key, kvPairInner.Value);
    }

    hashtable.Add(kvPair.Key, hashtableInner);
}

# Pass hashtable to PowerShell as even v2 understands .NET hashtables

Upvotes: 1

Related Questions