Manipulating with hashtable powershell

Can someone explain why we have different behaviors when we work with hash tables?

In fact, when the value is a simple type (integer, string ...) or an object type, the behavior is different. When we work with a simple type, and we influence the value of a variable and update it; this will not update the hash table. But when we work with the type of an object, we influence the value of the variable and update it; this will update the hash table.

This will be easier to understand with the ^^ example.

Simple type:

$hash=@{
    a=1
    b=2
}
$variable = $hash['a']
$variable = 3

Result: $hash
Name                           Value
----                           -----
a                              1
b                              2

Object type:

$hash=@{
    a=New-Object PSObject -Property @{ obj=1 }
    b=New-Object PSObject -Property @{ obj=2 }
}
$variable = $hash['a']
$variable.obj = 3

Result: $hash
Name                           Value
----                           -----
a                              @{obj=3}
b                              @{obj=2}
+4
source share
1 answer

This is because you are using reference types and value types .

Object type:

$variable = $hash['a']
$variable.obj = 3

.

:

$variable = $hash['a']
$variable = 3

int . , , , -. -, $hash['a'] = 3

.

: string , , . int.

+7

Source: https://habr.com/ru/post/1599482/


All Articles