Careful with Add-Member!

by Nov 11, 2016

Frequently, Add-Member is used to create custom objects, for example like this:

$o = New-Object -TypeName PSObject
$o | Add-Member -MemberType NoteProperty -Name Notes -Value 'Something'
$o | Add-Member -MemberType NoteProperty -Name Date -Value (Get-Date)

$o

This works, and the result looks like this:

 
PS C:\> $o 

Notes     Date                 
-----     ----                 
Something 10/28/2016 3:56:53 PM

However, it is inefficient because Add-Member is used to dynamically extend existing objects, not to create new ones. The above could much more easily be achieved like this:

$o = [PSCustomObject]@{
  Notes = 'Something'
  Date  = Get-Date
  }

$o

Add-Member can do much more advanced things, like adding script properties and methods. Check out what happens when you add a dynamic script property to above object:

$o = [PSCustomObject]@{
  Notes = 'Something'
  Date  = Get-Date
  }

$o | Add-Member -MemberType ScriptProperty -Name CurrentDate -Value { Get-Date }

Now watch the Date and CurrentDate properties when you query the object multiple times:

 
PS C:\> $o 

Notes     Date                  CurrentDate          
-----     ----                  -----------          
Something 10/28/2016 4:01:54 PM 10/28/2016 4:01:57 PM



PS C:\> $o 

Notes     Date                  CurrentDate          
-----     ----                  -----------          
Something 10/28/2016 4:01:54 PM 10/28/2016 4:02:00 PM



PS C:\> $o 

Notes     Date                  CurrentDate          
-----     ----                  -----------          
Something 10/28/2016 4:01:54 PM 10/28/2016 4:02:02 PM

While Date property returns a static information, CurrentDate property always reports the current time because its value is a script that gets executed each time someone queries the property.

Twitter This Tip! ReTweet this Tip!