Add-Member allows new members to be added to existing objects.
Starting with an empty object, it is possible to add new properties:
PS> $empty = New-Object Object
PS> $empty | Add-Member -Name New -Value 'Hello world' -MemberType NoteProperty
PS> $empty
New
---
Hello world
Add-Member may also add a ScriptProperty or a ScriptMethod. When writing script-based properties and methods, the reserved variable $this is used to refer to itself.
To add calculated properties, which are evaluated when viewed, use the following code:
PS> $empty = New-Object Object
PS> $empty | Add-Member -Name New -Value 'Hello world' -MemberType NoteProperty
PS> $empty | Add-Member -Name Calculated -Value { $this.New.Length } -MemberType ScriptProperty
PS> $empty
New Calculated
--- ----------
Hello world 11
Methods may be added as well, for example, a method to replace the word world in the new property:
PS> $empty = New-Object Object
PS> $empty | Add-Member -Name New -Value 'Hello world' -MemberType NoteProperty
PS> $params = @{
>> Name = 'Replace'
>> MemberType = 'ScriptMethod'
>> Value = { $this.New -replace 'world', 'everyone' }
>> }
PS> $empty | Add-Member @params
PS> $empty.Replace()
Hello everyone