【问题标题】:How to Create [PsCustomObject] with Properties AND Methods如何使用属性和方法创建 [PsCustomObject]
【发布时间】:2017-10-09 04:30:56
【问题描述】:

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

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

用于:

$Obj.Len_A()       # return 3
$Obj.A += @(8,9)   # @(5,6,7,8,9)
$Obj.Len_A()       # return 5

【问题讨论】:

  • 您的目标是什么版本的 PowerShell?

标签: powershell object methods


【解决方案1】:

您可能想要使用Add-Member cmdlet:

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

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

现在您可以使用以下方法调用该方法:

$Obj.Len_A()

【讨论】:

  • 好!但是 Add-Member 是很慢的功能,见learn-powershell.net/2014/01/11/…
  • 好吧,你可能构建一个性能critical脚本,否则你会在你的问题中提到这一点。因此,除非您的脚本实际运行缓慢,否则您可以放心地忽略所有性能比较...
【解决方案2】:

您没有提及您使用的是哪个版本的 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2021-12-17
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多