Basic demonstration of add-member
The following simple example of add-member creates a System.Object
object and adds the two member variables num
and text
. It also adds the member method twice
which multiplies the value of num
and assigns it to num
again.
$obj = new-object System.Object
$obj | add-member -memberType noteProperty -name num -value 21
$obj | add-member -memberType noteProperty -name text -value foo
$obj | add-member -memberType scriptMethod -name twice -value { $this.num *= 2 }
$obj.twice()
write-output "`The num is $($obj.num), text is $($obj.text)"
#
# The num is 42, text is foo
$obj | get-member
#
# TypeName: System.Object
#
# Name MemberType Definition
# ---- ---------- ----------
# Equals Method bool Equals(System.Object obj)
# GetHashCode Method int GetHashCode()
# GetType Method type GetType()
# ToString Method string ToString()
# num NoteProperty int num=42
# text NoteProperty string text=foo
# twice ScriptMethod System.Object twice();
Adding a script method
A script method adds member methods to an object. Within the script block that implements the method, the respective
object can be referred to with the
$this
automatic variable.
$num = new-object psObject @{
val = 4
txt = 'four'
}
$num | add-member scriptMethod dbl {
$this.val * 2
}
$num | add-member scriptMethod mult {
param([int]$i = 1)
$this.val * $i
}
$num.dbl()
#
# 8
$num.mult(7)
#
# 28
Get member's value by name stored in a variable
$obj.memberName
evaluates to the member whose name is
memberName
. If the name of the member is stored in a
variable, the name can be looked up with
$obj.$var
:
$cust_obj = new-object psObject
$cust_obj | add-member number 42
$cust_obj | add-member text 'hello world'
$cust_obj | add-member meta 'foo', 'bar', 'baz'
$member_name = 'text'
$cust_obj.$member_name
'number', 'text', 'meta' | foreach-object {
'{0,-6}: {1}' -f $_, $cust_obj.$_
}