Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

PowerShell Custom Objects

196 views
Skip to first unread message

ebgreen

unread,
Mar 26, 2008, 9:42:00 AM3/26/08
to
So I am familiar with making custom objects via:

$foo = "" | Select-Object Prop1,Prop2

This would of course create a System.Management.Automation.PSCustomObject
object with 2 NoteProperties (Prop1 and Prop2). My questions are:

Is it possible to add methods to the object?
Is it possible to override the ToString() method for the object?

Shay Levi

unread,
Mar 26, 2008, 10:03:22 AM3/26/08
to

To add a method:

PS > $foo = "" | Select-Object Prop1,Prop2
PS > $foo | Add-Member -pass scriptmethod newMethod {$this.prop1 + $this.prop2}
| out-null
PS > $foo.prop1=1
PS > $foo.prop2=1
PS > $foo.newMethod()
2

To override the default ToString() method add the -force parameter:

PS > $foo | Add-Member -pass scriptmethod -force ToString {"Overriding the
default ToString() method"} | out-null
PS > $foo.ToString()
Overriding the default ToString() method


-----
Shay Levi
$cript Fanatic
http://scriptolog.blogspot.com

ebgreen

unread,
Mar 26, 2008, 10:19:28 AM3/26/08
to
Thank you very much.

Shay Levi

unread,
Mar 26, 2008, 10:25:51 AM3/26/08
to

You can also use this syntax:

PS 12> $foo = "" | Select-Object Prop1,Prop2
PS 13> $newMethod = new-object system.Management.Automation.PSScriptMethod
newMethod,{$this.prop1+$this.prop2}
PS 14> $foo.psobject.members.add($newMethod)
PS 15> $foo.prop1=1
PS 16> $foo.prop2=1
PS 17> $foo.newMethod()
2

PS 18> $ToString= new-object system.Management.Automation.PSScriptMethod
ToString,{"bla bla bla"}
PS 19> $foo.psobject.members.add($ToString)
PS 20> $foo.ToString()
bla bla bla


-----
Shay Levi
$cript Fanatic
http://scriptolog.blogspot.com

> To add a method:


>
PS>> $foo = "" | Select-Object Prop1,Prop2
PS>> $foo | Add-Member -pass scriptmethod newMethod {$this.prop1 +

PS>> $this.prop2}


> | out-null
>
PS>> $foo.prop1=1
PS>> $foo.prop2=1
PS>> $foo.newMethod()
> 2
>
> To override the default ToString() method add the -force parameter:
>
PS>> $foo | Add-Member -pass scriptmethod -force ToString {"Overriding

PS>> the
PS>>

> default ToString() method"} | out-null
>
PS>> $foo.ToString()

PS>>

0 new messages