Reputation: 1418
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
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
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
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