Re: [msh] Best way to create objects, add properties in script?
- From: "Jouko Kynsijärvi" <jouko.kynsijarvi@xxxxxxxxxxxxx>
- Date: Fri, 21 Apr 2006 18:09:49 +0300
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
.
- Follow-Ups:
- Re: [msh] Best way to create objects, add properties in script?
- From: Jouko Kynsijärvi
- Re: [msh] Best way to create objects, add properties in script?
- Prev by Date: Re: Script to create subdirectories
- Next by Date: Re: Power Managment setting
- Previous by thread: SMS - checking for Advertised jobs
- Next by thread: Re: [msh] Best way to create objects, add properties in script?
- Index(es):