Google Groupes n'accepte plus les nouveaux posts ni abonnements Usenet. Les contenus de l'historique resteront visibles.

PowerShell Custom Objects

198 vues
Accéder directement au premier message non lu

ebgreen

non lue,
26 mars 2008, 09:42:0026/03/2008
à
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

non lue,
26 mars 2008, 10:03:2226/03/2008
à

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

non lue,
26 mars 2008, 10:19:2826/03/2008
à
Thank you very much.

Shay Levi

non lue,
26 mars 2008, 10:25:5126/03/2008
à

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 nouveau message