mardi 24 février 2015

"Add-Member" to a type instead of only an object of that type in PowerShell

In PowerShell you can extend objects :



The Add-Member cmdlet lets you add members (properties and methods) to an instance of a Windows PowerShell object. For example, you can add a NoteProperty member that contains a description of the object or a ScriptMethod member that runs a script to change the object.



However :



The properties and methods that you add are added only to the particular instance of the object that you specify. Add-Member does not change the object type. To create a new object type, use the Add-Type cmdlet...



Example :



$s = "Hello World" | Add-Member -PassThru ScriptProperty Reverse {$this[$this.Length..0] -join ""}

$s Hello World

$s.Reverse dlroW olleH


Is there a simple direct manner to do the same thing for all instances of that type, just like what Extension Methods do in C#, something that would do something somehow similar to the following :



$s = "Hello World" | Add-Member -PassThru ScriptProperty Reverse {$this[$this.Length..0] -join ""}

$s Hello World

$s.Reverse dlroW olleH

$a = "Aymen"
$a.Reverse nemyA

Aucun commentaire:

Enregistrer un commentaire