none
Hash Table Keys and Values

    Question

  • Guys I am trying to set the key and value of a hash table by getting the values of cells in 2 columns. I am having trouble, in that Powershell either complains the key is already added or it only loads the very last item from the columns, depending on the way I have tried to do it.

    $SpendingInfo=@{}

    Do {

    $a++

    $Category = $Worksheet.Cells.Item($a, 1).Value()

    $Spent = $Worksheet.Cells.Item($a,2).Value()

    $SpendingInfo += @{ $Category = $Spent}

    }

    until ($Worksheet.Cells.Item($a, 2).Value() = $null)

    It complains the '+=' operator failed: Item has already been added.

    Thanks for your help!

    

    



    • Edited by mario.exe Sunday, March 11, 2012 11:37 PM yet another typo.
    Sunday, March 11, 2012 6:54 PM

Answers

  • Ok sorry guys looks like column 1 has duplicate values, which is why it is complaining the key already exists. Thanks your attempts.
    • Marked as answer by mario.exe Monday, March 12, 2012 12:04 AM
    Monday, March 12, 2012 12:04 AM

All replies

  • try changing the first line to:

        $SpendingInfo+@{}

    And see what happens.


    Al Dunbar

    Sunday, March 11, 2012 7:36 PM
  • I think Al meant

    change that first line to:

    $SpendingInfo = @{}


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Sunday, March 11, 2012 10:04 PM
  • I must have made a typo when I was typing the code in when I asked the question, because I was having issues with it pasting. I actually have it as $SpendingInfo = @{} already.

    Sunday, March 11, 2012 10:59 PM
  • $SpendingInfo=@()
    Do {
    $a++
    $Category = $Worksheet.Cells.Item($a, 2).Value()
    $Spent = $Worksheet.Cells.Item($a,2).Value()
    $SpendingInfo += @{ $Category = $Spent}
    }
    Not sure it is normal, but $Category and $Spent, read the same cell
    Sunday, March 11, 2012 11:15 PM
  • fixed the typo in the code, it reads values from column 1 and 2, when i load the hash table with the += .Powershell complains, with  the key is already added
    • Edited by mario.exe Sunday, March 11, 2012 11:52 PM
    Sunday, March 11, 2012 11:51 PM
  • Ok sorry guys looks like column 1 has duplicate values, which is why it is complaining the key already exists. Thanks your attempts.
    • Marked as answer by mario.exe Monday, March 12, 2012 12:04 AM
    Monday, March 12, 2012 12:04 AM
  • I think Al meant

    change that first line to:

    $SpendingInfo = @{}


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Nice catch. Or perhaps I meant just to change it *from* what it was, without specifying what it should be changed to...

    Actually, I was thinking more of an array @() than of a hash table @{}...


    Al Dunbar

    Tuesday, March 13, 2012 8:14 PM