Why is this property not updating when I pass it by reference in PowerShell
Can someone please explain why the property update is not persisting after the function exits the example below.
function CreateConfigObject
{
# base solution directory
$Config = New-Object -typename PSObject
# Build Config File Contents
$Config | Add-Member -Name MyProperty -MemberType NoteProperty -Value "Original Value"
return $Config
}
function MyFunction([ref]$obj)
{
Write-Host "Inside function Before Updating : " $obj.Value
Write-host "Are the objects equal? " $obj.Value.Equals($config.MyProperty)
$obj.Value = "New Value"
Write-Host "Inside function After Updating : " $obj.Value
}
$config = CreateConfigObject
Write-Host "Before calling function : " $config.MyProperty
MyFunction ([ref]$config.MyProperty)
Write-Host "After calling function : " $config.MyProperty
+3
source to share
1 answer
Thought a little, but I have an answer. [ref] passes an object, not a value, to a function. So what you need to do is pass a $config
function and then specify its value and property of .MyProperty
that value. Take a look at this slightly modified code to see my point:
function CreateConfigObject
{
# base solution directory
$Config = New-Object -typename PSObject
# Build Config File Contents
$Config | Add-Member -Name MyProperty -MemberType NoteProperty -Value "Original Value"
return $Config
}
function MyFunction([ref]$obj)
{
Write-Host "Inside function Before Updating : " $obj.value.MyProperty
Write-host "Are the objects equal? " $obj.value.MyProperty.Equals($config.MyProperty)
$obj.value.MyProperty = "New Value"
Write-Host "Inside function After Updating : " $obj.value.MyProperty
}
$config = CreateConfigObject
Write-Host "Before calling function : " $config.MyProperty
MyFunction ([ref]$config)
Write-Host "After calling function : " $config.MyProperty
This will produce the expected results:
Before calling function : Original Value
Inside function Before Updating : Original Value
Are the objects equal? True
Inside function After Updating : New Value
After calling function : New Value
+4
source to share