When I run this code it results in $o having a Name property with no value, even though I passed ‘MyObj’ as the name. What am I doing wrong?
Thanks for any help.
function CreateSomething {
param( [string] $name )
$o = new-object PSObject
write-host '$name:' $name
$o | add-member -name Name -passThru -force -memberType ScriptProperty -value { $name }
$o
}
$o = CreateSomething -name MyObj
$o
What are you trying to achieve here?
The
-value { $name }will be the scriptblock that is used for the ScriptProperty and it has no idea of$name( it is not in scope)You can do it this way:
I don’t see why you can’t just do:
Note: Since you are using
-passThruin the above statement, you can omit the lone$oin the last line of your function.