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
1 2 3 4 |
$Obj = Get-Item C:\test $Obj| Add-Member -MemberType NoteProperty -Name Size -Value 2048 |
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:
1 2 3 4 |
$Obj = Get-Item C:\test $Obj| Add-Member -NotePropertyName Size -NotePropertyValue 2048 |
You can check the value of a Size
property of the object in $Obj
.
1 2 3 |
$Obj.Size |
Output:
1 2 3 |
2048 |
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.