This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi /r/powershell,
I came across a behavior that I can't explain. I think it has something to do with referencial variables, but I'm not sure. I tried to narrow it down to a simple example, and I hope I can explain it. I am very confused ...
Let's say I have a refernce object. I compare it to a difference object using a function. In that function I copy the values from the reference object to the difference object, and output a new custom object that contains both objects.
Function New-ReferenceObject {
Param (
[String]$value1,
[String]$value2
)
[PsCustomObject] @{
'Prop1' = $value1
'Prop2' = $value2
}
}
Function New-DifferenceObject {
Param (
[String]$value1
)
[PsCustomObject] @{
'Prop1' = $null
'Prop2' = $null
'Prop3' = $value1
}
}
Function New-Evaluation{
Param (
[PsCustomObject]$Reference,
[PsCustomObject]$Difference
)
$Difference.Prop1 = $Reference.Prop1
$Difference.Prop2 = $Reference.Prop2
[PsCustomObject] @{
'Reference' = $Reference
'Evaluated' = $Difference
}
}
So I create two objects $Reference1
and $Difference
...
$Reference1 = New-ReferenceObject -value1 5 -value2 10
$Difference = New-DifferenceObject -value1 5
PS C:\Windows\system32> $Reference1
Prop1 Prop2
----- -----
5 10
PS C:\Windows\system32> $Difference
Prop1 Prop2 Prop3
----- ----- -----
5
and save the output of the evaluation in Evaluated1
:
$Evaluated1 = New-Evaluation-Reference $Reference1 -Difference $Difference
PS C:\Windows\system32> $Evaluated1
Reference Evaluated
--------- ---------
@{Prop1=5; Prop2=10} @{Prop1=5; Prop2=10; Prop3=5}
So far, everything is as expected. However, if I create a second reference object, evaluate it against the same difference object, and store it in $Evaluated2
, the content of $Evaluated1
is changed:
$Reference2 = New-ReferenceObject -value1 20 -value2 30
PS C:\Windows\system32> $Reference2
Prop1 Prop2
----- -----
20 30
$Evaluated2 = New-Evaluation-Reference $Reference2 -Difference $Difference
PS C:\Windows\system32> $Evaluated1
Reference Evaluated
--------- ---------
@{Prop1=5; Prop2=10} @{Prop1=20; Prop2=30; Prop3=5}
The Evaluated
property of $Evaluated1
now contains the values of $Reference2
, although I never altered it.
What is going on here?
Subreddit
Post Details
- Posted
- 6 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/PowerShell/...