Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is this Property not being updated when I pass it by reference in PowerShell

Tags:

powershell

Could somebody please explain why the update to the property is not being persisted after the function exits in 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
like image 368
samaspin Avatar asked Dec 10 '25 09:12

samaspin


1 Answers

Took a bit of figuring, but I've got an answer. [ref] passes an object, not a value, to a function. So what you would need to do is pass $config to the function, and then reference it's value, and the .MyProperty property of that value. Look at this slightly altered 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

That will output 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
like image 196
TheMadTechnician Avatar answered Dec 12 '25 23:12

TheMadTechnician



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!