Below is my code. I would like to add then read individual values.
$ht = @{
'Hcohesity01' = @{
'Audit' = 1
'Block' = 2
'Change' = 3
'percentage' = @{
'server1' = 4
'server2' = 5
'server3' = 10
}
}
'Hcohesity02' = @{
'Audit' = 1
'Block' = 2
'Change' = 3
'percentage' = @{
'server1' = 4
'server2' = 5
'server3' = 10
}
}
}
$ht['Hcohesity02']['percentage']['server4'] = 20
foreach ( $value -in $ht['Hcohesity02']['percentage'].Values){
$server5 = $value
}
$ht['Hcohesity02']['percentage']['server5'] =$server5
$ht['Hcohesity02']['percentage']
Below code is not working , any idea ? foreach ( $value -in $ht['Hcohesity02']['percentage'].Values)
CodePudding user response:
The only real mistake in your code is by writing -in
in the foreach loop. That should have been just in
.
Instead of using a loop to add-up the values, you can use a one-liner with Measure-Object
:
$ht = @{
'Hcohesity01' = @{
'Audit' = 1
'Block' = 2
'Change' = 3
'percentage' = @{
'server1' = 4
'server2' = 5
'server3' = 10
}
}
'Hcohesity02' = @{
'Audit' = 1
'Block' = 2
'Change' = 3
'percentage' = @{
'server1' = 4
'server2' = 5
'server3' = 10
}
}
}
$ht['Hcohesity02']['percentage']['server4'] = 20
# instead of a foreach loop:
# $server5 = 0 # initialize
# foreach ( $value in $ht['Hcohesity02']['percentage'].Values) {
# $server5 = $value
# }
# you can do this:
$server5 = ($ht['Hcohesity02']['percentage'].Values | Measure-Object -Sum).Sum
$ht['Hcohesity02']['percentage']['server5'] = $server5
$ht['Hcohesity02']['percentage']
Result:
Name Value
---- -----
server2 5
server5 39
server3 10
server1 4
server4 20
If you don't like addressing the properties with the [property]
syntax, you can also use dot notation as hoppy7 showed in his answer:
$ht.'Hcohesity02'.'percentage'.Values # and so on
CodePudding user response:
Its not quite clear what you're trying to do. If its just iterating through your foreach loop and assigning a value, you need to ditch the dash on "-in". It should look like the below:
foreach ($value in $ht.Hcohesity02.percentage.Values)
{
# do some stuff
}