Can a hash table be inside a variable?

Welcome Forums General PowerShell Q&A Can a hash table be inside a variable?

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
3 months, 4 weeks ago.

  • Author
    Posts
  • #104801

    Participant
    Points: 109
    Rank: Participant

    I have a simple hash table application. My dilemma is that the key-value pairs are all inside a CSV file.
    Will Powershell accept something like:

    $x = @{$HashTab}

    where $HashTab (if displayed to the console) has the contents:

    '123'='Smith, James';
    '301'='Jones, Debbie';
    ...
    '910'='Anders, Roy';

    After this, I then want to do something like a table lookup, i.e.,
    $key = '301'
    $Keyvalue = $x.$key

    Any hints, tips or better ways of doing it "the Powershell way" would be highly appreciated.
    Much thanks!

  • #104821

    Participant
    Points: 144
    Helping Hand
    Rank: Participant

    If $HashTab already is a hash table what for do you need to assign it to another variable?

    $HashTab = @{
    '123'='Smith, James'
    '301'='Jones, Debbie'
    '910'='Anders, Roy'
    }
    
    $key = '301'
    $keyvalue = $HashTab.$key
    $keyvalue

    Please format your code as code. Thanks

    • #104828

      Participant
      Points: 109
      Rank: Participant

      Hello,

      Thanks for your reply. The Contents of my hash table are sitting in an external file.
      Short of typing the contents (rather long, about 500 entries) of that file into my PS script, I would like to know if those contents can be read into a variable as described in my initial post.

  • #104825

    Participant
    Points: 165
    Helping Hand
    Rank: Participant

    If the above is what your string data looks like, then you might want to look into using the ConvertFrom-StringData cmdlet to get it into hashtable form. 🙂

    • #104836

      Participant
      Points: 109
      Rank: Participant

      Many thanks Mr Sallow. I have just tried it and it works beautifully. The documentation suggests the command can do a lot more, I'm happy to have come across this piece of know-how.

      My sincerest gratitude for your help.
      Best,

The topic ‘Can a hash table be inside a variable?’ is closed to new replies.