Tagging Objects Efficiently

by Dec 1, 2017

Occasionally you see scripts that use Select-Object to append information to existing objects. This can look similar to the code below:

Get-Process | 
    Select-Object -Property *, Sender|
    ForEach-Object { 
        $_.Sender = $env:COMPUTERNAME

It does work, but Select-Object creates a complete object copy, so this approach is slow and changes the object type. You’ll notice that PowerShell no longer outputs the process objects with the usual table design because of this.

Add-Member is the premier cmdlet to add more info to existing objects because it does not copy objects and does not change object types. Just compare the output:

Get-Process |
  Add-Member -MemberType NoteProperty -Name Sender -Value $env:COMPUTERNAME -PassThru

The object type is unchanged, and PowerShell continues to use the default output layout for processes. This coincidentally is why the new “Sender” property initially is not visible. It is present, though:

Get-Process |
  Add-Member -MemberType NoteProperty -Name Sender -Value $env:COMPUTERNAME -PassThru |
  Select-Object -Property Name, Id, Sender

Twitter This Tip! ReTweet this Tip!