NoteProperty and ScriptProperty - what is(are) the fundamental differences?

I am trying to expand on my understanding of these 2 “member types.”

To date, my understanding is that NoteProperty comes from the “original data”, such as an imported CSV file. ScriptProperty is when the [presumably new, and created for a specific reason] property is created with, say, Add-member, as in:

Add-member -Membertype ScriptProperty -Name "NewProp2" -Value {...}

But Add-member also admits NoteProperty in -Membertype parameter. So what’s the difference? When would I use something like:

Add-member -Membertype NoteProperty -Name "XXX"

A second question: when I write:

[PSCustomObject]@ { ...}

is this not a script block? or just a hash table? If script block, is it the case then, that the properties defined by the Name= and Expression= pairs inside the curly brackets are all ScriptProperty(ies)?

My apologies if this question does not make sense, but I am most likely missing some basic feature or concept of the various kinds of properties within Powershell.

Any tips, pointers or references to detailed explanations would be appreciated. Many thanks in advance.

 

@{ } is a hashtable, while { } is a script block. @ { } is a syntax error. :wink:

[PSCustomObject]@{} uses parser magic to generate a PSObject with NoteProperties.

NoteProperties are static; they remain whatever value you give them at the time of creation or assignment. These are what are created with the [PSCustomObject]@{Name = ‘Value’} syntax.

ScriptProperties are not. If you give them a value that references another property on the object, and that other property changes, their value also changes. As a result, ScriptProperties are often slower to retrieve values for than NoteProperties, as you’re often evaluating code when calling the property. These can only be created with Add-Member, or manually using $object.PSObject.Properties.Add( [psscriptproperty]::new($name,$value) ).

Demonstration:

https://gist.github.com/vexx32/34194d3c4df40a5ae8bad0776094c9e5

 

Sincerest thanks, Joel.
Much appreciated!

As per the highly recommended book… ‘PowerShell in Action - Bruce Payette’

...

A ‘ScriptProperty’ has up to two methods associated with it – a getter and (optionally) a setter, just like a .NET property. These methods are expressed using two scriptblocks. As was the case with say a ‘ScriptMethod’, the referenced object is available in the $this member and in the case of the setter, the value being assigned is available in $args[0].

A ‘NoteProperty’ is a way of attaching a new piece of data (a note) to an existing object, rather like putting a sticky note on your monitor.


 

Thanks very much, Mr/Ms Postanote. This is very helpful.