Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, April 2, 2014 9:42 PM
I am trying to update the Value of a hash table, if there is a True condition. My false condition works fine. I am unclear how to update the value in a hash table, if there is a key that is true.
thank you for your help
File.csv
name,count
a,1
b,2
c,10
d,11
the $hash table results would be.
"a=1","b=2","c=13","d=11"
Script:
$import = import-csv ("c:\file.csv")
$Hash=@{
"a"="1";"b"="2";"c"="3"
}
foreach ($item in $import)
{
$Importedname = $item.name
$Importedcount = $item.count
if ($hash.ContainsKey($Importedname))
{
Write-Host "True" $Importedname
}
Else
{
$hash.Add("$Importedname","$Importedcount")
Write-Host "False"
}
}
All replies (4)
Thursday, April 3, 2014 12:16 AM âś…Answered
It's unusual to call the set_Item method like that. Typically, you'll see this syntax instead:
$hash['c'] += 10
However, be careful of how you defined your hashtable. Right now, the values are strings instead of numbers, and "3" + 10 would produce the string "310". Instead, define the hashtable to contain integers:
$Hash=@{
"a" = 1
"b" = 2
"c" = 3
}
$Hash['c'] += 10
$Hash
Wednesday, April 2, 2014 10:07 PM
Try this using the Set_Item Method:
$import = import-csv ("c:\file.csv")
$Hash=@{
"a"="1"
"b"="2"
"c"="3"
}
foreach ($item in $import)
{
$Importedname = $item.name
$Importedcount = $item.count
if ($hash.ContainsKey($Importedname))
{
Write-Host "True" $Importedname
$Hash.set_Item($Importedname,$Importedcount)
}
Else
{
$hash.Add("$Importedname","$Importedcount")
Write-Host "False"
}
}
P.s:
If you would like to see all the methods type $Hash | Get-Member -Force
Wednesday, April 2, 2014 10:39 PM
Thank you for your reply. the only issue, I need to add the two values. So, $hash c=3, and $item c=10 would need to update the $hash value c=3 to be, c=13. is there a way to add the two values and then update it with the set_item.
Thursday, April 3, 2014 12:21 AM
thank you that worked.