2017-05-10 25 views
1

我嘗試定義像這樣的自定義方法的對象,但我syntaxe是錯誤的:如何創建具有屬性和方法[PsCustomObject]

$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 
+2

您定位的是哪個版本的PowerShell? –

回答

3

你可能要使用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() 
+0

好!但添加成員是非常慢的功能,請參閱https://learn-powershell.net/2014/01/11/custom-powershell-objects-and-performance-revisited/ – Alban

+0

那麼,你可能*不*建立一個性能*關鍵*腳本,否則你會在你的問題中提到。因此,除非腳本實際運行緩慢,否則您可以放心地忽略所有性能比較器。 –

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() 
相關問題