Add-Member

Getting to Know Add-Member in PowerShell

Welcome back to Wahmans PowerShell blog! Today, we’re delving into a powerful feature in the PowerShell scripting world: the Add-Member cmdlet.

According to Microsoft: Add-Member adds custom properties and methods to an instance of a PowerShell object.

This mighty cmdlet allows you to enrich existing objects with new data or behaviors, giving you the ability to customize objects as needed. Let’s walk through four examples, from beginner to more advanced, to show you how Add-Member can elevate your PowerShell scripts!

Example 1: Adding a Simple NoteProperty to a Custom Object

$obj = New-Object PSObject
Add-Member -InputObject $obj -MemberType NoteProperty -Name "Name" -Value "John Doe"
Add-Member -InputObject $obj -MemberType NoteProperty -Name "Age" -Value 30
$obj

This is a basic use case. We create a generic object and add properties to it. This can be helpful when dynamically creating report objects or temporary data structures.

Example 2: Enrich Output of Existing Cmdlets

$service = Get-Service -Name "wuauserv"
Add-Member -InputObject $service -MemberType NoteProperty -Name "CheckedBy" -Value $env:USERNAME
$service | Format-List Name, Status, CheckedBy

Here, we take an object returned by Get-Service and add a custom property marking who checked the service. This is quite practical when auditing or creating enriched logs.

Example 3: Adding a ScriptMethod

$person = New-Object PSObject
Add-Member -InputObject $person -MemberType NoteProperty -Name FirstName -Value "Jane"
Add-Member -InputObject $person -MemberType NoteProperty -Name LastName -Value "Doe"
Add-Member -InputObject $person -MemberType ScriptMethod -Name GetFullName -Value { return "$($this.FirstName) $($this.LastName)" }

$person.GetFullName()

In this intermediate example, we not only add properties, but also a method! The ScriptMethod lets you define behavior—a simple method that returns the full name of a person.

Example 4: Dynamically Extend Objects in a Pipeline

Get-Process | ForEach-Object {
    Add-Member -InputObject $_ -MemberType NoteProperty -Name TimeStamp -Value (Get-Date) -PassThru
} | Select-Object Name, Id, TimeStamp

Advanced PowerShell users will appreciate how this allows per-object enrichment in a pipeline. We add a TimeStamp to every process object as it’s being processed—ideal for detailed logging or profiling scenarios.

Conclusion

Add-Member is a powerful yet often underutilized cmdlet. It gives you the flexibility to decorate your objects with the additional data and functionality that best fits your task at hand. From automation to reporting, this tool is worth adding to your everyday scripting arsenal.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *