Inheriting objects in powershell

Hi Gurus,

I have created a custom object using this method, 

$object = New-Object Object |            
    Add-Member NoteProperty MyField 5 -PassThru |             
    Add-Member ScriptMethod xTimesMyField {            
        param($x)            
        $x * $this.MyField            
        } -PassThru            
                
$object            
$object.xTimesMyField(10)   

Now I want to create another object that inherits the properties and methods of this object. How do I do that ?

April 10th, 2012 2:37am

You are thinking of a class.  Powershell does not support classes.  The best you can do is use "Clone" to create a copy of the object.

$object2 = $object.Clone()

Free Windows Admin Tool Kit Click here and download it now
April 10th, 2012 8:21am

The $object in the example above doesn't have the "Clone" method, so I don't think this answer is complete.

I've worked around it like this :

Function New-CustomObject {
    $object = New-Object Object |            
    Add-Member NoteProperty MyField 5 -PassThru |             
    Add-Member ScriptMethod xTimesMyField {            
        param($x)            
        $x * $this.MyField            
        } -PassThru            
    return $object
    }
        
$object1 = New-CustomObject        
$object2 = New-Customobject
        
$object1.Myfield = 5
$object2.Myfield = 10


$objects = @()
$objects += $object1
$objects += $object2

$objects | ft -autosize


$object1.xTimesMyField(10)
$object2.xTimesMyField(10)

January 10th, 2014 6:12am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics