How to Create [PsCustomObject] with Properties AND Methods How to Create [PsCustomObject] with Properties AND Methods powershell powershell

How to Create [PsCustomObject] with Properties AND Methods


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()