Add Property to Object in PowerShell

Using Add-Member cmdlet

The Add-Member cmdlet allows you to add members (properties and methods) to an object in PowerShell.

To add property to a PowerShell object:

  • Pipe an object to the Add-Member cmdlet followed by the property to add

In the first command, Get-Item C:\test gets the DirectoryInfo object which is saved in a variable $Obj. The $Obj is piped to Add-Memeber which adds the note property named Size with a value 2048 to an object in $Obj.

-MemberType: Specifies the member type to add

-Name: Specifies the name of a member

-Value: Specifies the value of a member

In Windows PowerShell 3.0, the following two parameters were introduced, making adding the note property to an object easier.

-NotePropertyName: To specify the note property name

-NotePropertyValue: To specify the note property value

Therefore, the previous code can also be written as:

You can check the value of a Size property of the object in $Obj.

Output:

As it returned the added value, it means we have successfully added a new property to the object in $Obj.

That’s all about how to add property to object in PowerShell. If you have any confusion, let us know in the comments.

For more information, read about Add-Member.

Was this post helpful?

Leave a Reply

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