Hash Table Keys and Values
-
Sunday, March 11, 2012 6:54 PM
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!
All Replies
-
Sunday, March 11, 2012 7:36 PM
try changing the first line to:
$SpendingInfo+@{}
And see what happens.
Al Dunbar
-
Sunday, March 11, 2012 10:04 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:59 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 11:15 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:51 PMfixed 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
-
Monday, March 12, 2012 12:04 AM
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
-
Tuesday, March 13, 2012 8:14 PM
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

