$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?
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
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>>