Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create [PsCustomObject] with Properties AND Methods

I try to define an object with custom methods like this but my syntaxe is wrong:

$Obj = [pscustomobject]@{
    A = @(5,6,7)
    B = 9
    Len_A = {return $this.A.count;}
    Sum_A = {return (SumOf $this.A);}
}

for use like :

$Obj.Len_A()       # return 3
$Obj.A += @(8,9)   # @(5,6,7,8,9)
$Obj.Len_A()       # return 5
like image 909
Alban Avatar asked May 10 '17 13:05

Alban


People also ask

Which cmdlet displays the properties and methods of an object?

The Get-Member cmdlet gets the members, the properties and methods, of objects. To specify the object, use the InputObject parameter or pipe an object to Get-Member .

How do I add a property to a PowerShell object?

The Add-Member cmdlet lets you add members (properties and methods) to an instance of a PowerShell object. For instance, 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.

What is the difference between PSObject and PSCustomObject?

[PSCustomObject] is a type accelerator. It constructs a PSObject, but does so in a way that results in hash table keys becoming properties. PSCustomObject isn't an object type per se – it's a process shortcut. ... PSCustomObject is a placeholder that's used when PSObject is called with no constructor parameters.


2 Answers

You probably want to use the Add-Member cmdlet:

$Obj = [pscustomobject]@{
    A = @(5,6,7)
    B = 9
}

$Obj | Add-Member -MemberType ScriptMethod -Name "Len_A" -Force -Value {
    $this.A.count 
} 

Now you can call the method as expected using:

$Obj.Len_A()
like image 76
Martin Brandl Avatar answered Nov 15 '22 00:11

Martin Brandl


You did not mention which version of powershell you are using. If you want object-orientation use class like this.

class CustomClass {
     $A = @(5,6,7)
     $B = 9
     [int] Len_A(){return $this.A.Count}
     [int] Sum_A(){
       $sum = 0
       $this.A | ForEach-Object {$sum += $_}
      return $sum
     }
}

$c = New-Object CustomClass
$s = $c.Sum_A()
$l = $c.Len_A()
like image 41
Ramana Avatar answered Nov 14 '22 22:11

Ramana