The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

goldfinger (9) [Avatar] Offline
#1
hallo
I have an understandig problem why the last example with add-member does working and there is an automatic object type change.

Example 1.
Not working:
$k=[datetime]::now
$k | add-member -membertype noteproperty -name meeting -value "Powershell Workshop"
$k | get-member
$k -is [PSObject]
False -> Thats the problem

Example 2.
Working:
$l= [PSObject]([DateTime]::Now)
# $l= ([DateTime]::Now) -as [PSObject]
$l | add-member -membertype noteproperty -name meeting -value "Powershell Workshop"
$l | get-member
PS:> meeting NoteProperty System.String meeting=Powershell
$l -is [PSObject]
True

Example 3.
Working but why?
$k=[datetime]::now
$k -is [PSObject]
False
$k.hour -> show one attribute and object type is changed but why?
$k -is [PSObject]
True

$k | add-member -membertype noteproperty -name meeting -value "Powershell Workshop"
$k | get-member
PS:> meeting NoteProperty System.String meeting=Powershell
brucepay (155) [Avatar] Offline
#2
Re: add-member understanding problem
Objects are wrapped as late as possible for a couple of reasons. First, if you're just performing a simple operation like adding two numbers, wrapping an integer and then unwrapping it slows things down quite a bit. The second issue is aliasing - once an object is wrapped, you have two ways of referring to the object - a reference to the wrapper and a reference to the wrapped object.

So - we only wrap objects when we have to or when it's otherwise expedient to do so. For example, when you reference a property or method on an object, we create a wrapper to do that reference but instead of discarding the wrapper object, we update the variable in place. This is what you see in your example 3.

When using Add-Member, if you always follow the pattern:

$obj = $obj | Add-Member -pass ...

then you won't run into a this problem. Alternatively you can use explicit casts as you showed in your example 2.

We understand that this is not great behaviour and we're working on improving it in PowerShell version 2. I'll add a note to the book updates that will go into more detail on this topic.

-bruce