PowerShell for Non-N00bs: [PSObject]::AddNodeProperty – the Missing Link

We all know PSH can output objects.  When the cmdlets or input give it objects to work with, outputting objects is easy.  However, when the program is dealing in strings and objects are required, things get long.

PS> $psobject = New-Object PSObject

PS> Add-Member -MemberType NoteProperty -InputObject $psobject -name "NotePropertyName1" -value "NoteProperty Value 1"

PS> Add-Member -MemberType NoteProperty -InputObject $psobject -name "NotePropertyName2" -value "NoteProperty Value 2"

and so on...

 It's actually pretty straightforward, but rather verbose.  How about this instead?

PS> Add-Member -InputObject $psobject-MemberType ScriptMethod -name AddNoteProperty -value { Add-Member -InputObject $this -MemberType NoteProperty -name $args[0] -value $args[1] }

PS> $psobject("NotePropertyName1", "NoteProperty Value1")

PS> $psobject("NotePropertyName2", "NoteProperty Value2")

Comments (0)

Skip to main content