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
                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 .
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.
[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.
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()
                        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()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With