Jamesla
Jamesla

Reputation: 1418

Change property on existing powershell object

I have a custom powershell object created with a function:

$obj = myfunction -name "hello" -value 5

After it's created I want to change the value property however doing it (demonstrated below) doesn't work

$obj.value = 1

I've searched and can't seem to find anything - can anybody explain how I can accomplish this?

Here is my function that creates an returns the object

function myfunction
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    Param
    (
        [Parameter(Mandatory=$true,
               Position=0)]
        [String]
        $name,

        [Parameter(Mandatory=$true,
               Position=1)]
        [int]
        $value,
    )
    Process
    {
        $myfunction = @{
            name = $name
            value = $value
        }
        write-output $myfunction
    }
}

Upvotes: 0

Views: 1465

Answers (3)

Stevie P
Stevie P

Reputation: 11

The OP is correct it does not work. It should be,

$obj."Hello" to access the property value

$obj."Hello" = 1 to set the property.

You have to double quote the property name.

Upvotes: 0

Jaykul
Jaykul

Reputation: 15824

If you're returning a hashtable, you should be able to do what you wrote:

PS> $obj = myfunction -name "hello" -value 5
PS> $obj.value = 1
PS> $obj

Name                           Value
----                           -----
name                           hello
value                          1

However, the "safe" way is to use square braces.

You might want to try that, because my gut is that you tried to set .Values instead of .Value ... and .Values is a non-settable property of Hashtables.

PS> $obj = myfunction -name "hello" -value 5
PS> $obj["value"] = 1
PS> $obj

Name                           Value
----                           -----
name                           hello
value                          1

Either way, you could avoid all that by creating an actual PSCustomObject as @jaqueline-vanek did in her answer.

Upvotes: 3

Jaqueline Vanek
Jaqueline Vanek

Reputation: 1133

PS C:\Users\joshua> $obj = [PSCustomObject]@{ hello = 5 }
PS C:\Users\joshua> $obj.hello
5
PS C:\Users\joshua> $obj.hello = 1
PS C:\Users\joshua> $obj.hello
1

PowerShell: Creating Custom Objects

Upvotes: 2

Related Questions