PowerShell function for adding elements to an array

后端 未结 2 1784
甜味超标
甜味超标 2021-01-16 05:31

I\'m still quite new to PowerShell and am trying to create a few functions that weaves together for creating and administrating an array. And I\'m having some problems with

2条回答
  •  自闭症患者
    2021-01-16 05:42

    Arrays don't have an .insert() method, but collections do. An easy way to produce a collection from an array is to use the .invoke() method of scriptblock:

    $array = 5,5,4,5,5
    
    $collection = {$array}.invoke()
    $collection
    $collection.GetType()
    
    5
    5
    4
    5
    5
    
    IsPublic IsSerial Name                                     BaseType                                  
    -------- -------- ----                                     --------                                  
    True     True     Collection`1                             System.Object                             
    

    Now you can use the .insert() method to insert an element at an arbitrary index:

    $collection.Insert(2,3)
    $collection
    
    
    5
    5
    3
    4
    5
    5
    

    If you need it to be an array again, an easy way to convert it back to an array is to use the pipeline:

    $collection | set-variable array
    $array
    $array.GetType()
    
    5
    5
    3
    4
    5
    5
    
    IsPublic IsSerial Name                                     BaseType                                  
    -------- -------- ----                                     --------                                  
    True     True     Object[]                                 System.Array                              
    

提交回复
热议问题