Re: [msh] Best way to create objects, add properties in script?

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



forestial wrote:
#create an empty object
$o = new-object system.management.automation.mshobject
# give it some properties
$o | add-member noteproperty foo 42

Or I can do this:
#create an empty object
$p = new-object system.management.automation.mshobject
# give it some properties
$p | select-object @{n="foo";e={42}} -outvariable p

These seem to lead to the same result
$o | fl

foo : 42

$p | fl

foo : 42

OK so far (except entering that long typename parameter to the
new-object cmdlet is tedious).

Now I try to access the properties of my new objects but I can't get
this to work.

$o.foo

seems to return $null. ($p.foo is the same).

Is this because foo is a noteproperty (rather than a property)? How
would I access it if I wanted to use it in some kind of expression?

Are you sure $o.foo didn't return anything? When tried the following:

$o = new-object system.management.automation.mshobject
$o | add-member noteproperty foo 42
$o.foo

$p = new-object system.management.automation.mshobject
$p | select-object @{n="foo";e={42}} -outvariable p
$p.foo

$o.foo outputted 42 and $p.foo outputted nothing. The reason for this is
that $p is a single object and $p is a list of objects (0..n):

$o.gettype().fullname
System.Management.Automation.MshCustomObject

$p.gettype().fullname
System.Collections.ArrayList

One way to fix this is:

$p = new-object system.management.automation.mshobject
$p | select-object @{n="foo";e={42}} -outvariable p
$p[0].foo
# or
$($p).foo


.