如何使用属性和方法创建[PsCustomObject]

Alb*_*ban 3 methods powershell object

我尝试使用这样的自定义方法定义对象,但是我的语法错误:

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

使用方式如下:

$Obj.Len_A()       # return 3
$Obj.A += @(8,9)   # @(5,6,7,8,9)
$Obj.Len_A()       # return 5
Run Code Online (Sandbox Code Playgroud)

Mar*_*ndl 5

您可能要使用Add-Membercmdlet:

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

$Obj | Add-Member -MemberType ScriptMethod -Name "Len_A" -Force -Value {
    $this.A.count 
} 
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用以下方法调用预期的方法:

$Obj.Len_A()
Run Code Online (Sandbox Code Playgroud)


小智 5

您没有提到您使用的是哪个版本的 powershell。如果你想要面向对象使用这样的类。

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()
Run Code Online (Sandbox Code Playgroud)