代码之家  ›  专栏  ›  技术社区  ›  Eric Schoonover thSoft

PowerShell将成员添加到数组项

  •  4
  • Eric Schoonover thSoft  · 技术社区  · 16 年前

    任何方法都可以显示此脚本 isPrime

    $p = @(1)
    $p[0] | %{ add-member -inputobject $_ -membertype noteproperty -name isPrime -value $true; $_ | gm }
    $p[0] | gm
    

       TypeName: System.Int32
    
    Name        MemberType   
    ----        ----------   
    CompareTo   Method       
    Equals      Method       
    GetHashCode Method       
    GetType     Method       
    GetTypeCode Method       
    ToString    Method       
    isPrime     NoteProperty 
    
    
    CompareTo   Method      
    Equals      Method      
    GetHashCode Method      
    GetType     Method      
    GetTypeCode Method      
    ToString    Method 
    
    2 回复  |  直到 16 年前
        1
  •  5
  •   Keith Hill    16 年前

    您遇到的问题是,1(整数)是中的值类型。NET,当它被传递时,它会被复制(按值传递)。因此,您成功修改了1的副本,但没有修改数组中的原始副本。如果你将1框(或强制)到一个对象(引用类型)上,你可以看到这一点,例如:

    $p = @([psobject]1)
    $p[0] | %{ add-member NoteProperty isPrime $true; $_ | gm }
    $p[0] | gm
    

    OP(spoon16)答案

    这就是我脚本中的代码最终的样子。如果可以优化,请随时编辑。

    $p = @() #declare array
    2..$n | %{ $p += [psobject] $_ } #initialize
    $p | add-member -membertype noteproperty -name isPrime -value $true
    
        2
  •  2
  •   Doug Finke    16 年前

    我会通过减少输入来优化:

    $p | add-member noteproperty isPrime $true
    
    推荐文章