Array question

This topic contains 4 replies, has 4 voices, and was last updated by  js 2 weeks, 4 days ago.

  • Author
    Posts
  • #100264

    dorinp4
    Participant

    Hello guys, i realy need your help.
    Basically:

    So have a array:

    Column1
    ——–

    2
    3
    5
    7

    And i want to subtract a numbere for example given by read host...lets say 7.

    In such a way that my finall resul will get something like

    Column1
    ———
    0
    0
    3
    5
    7

  • #100266

    dorinp4
    Participant

    Oopss,

    Final result like

    Column1
    ——–
    0
    0
    3
    7

    • #100297

      js
      Participant

      https://stackoverflow.com/questions/12860830/how-do-i-populate-an-array-of-unkown-length-in-powershell (works in pwsh core too)

      PS /> [arraylist # press tab
      PS /> [System.Collections.ArrayList 
      PS /> [collections.arraylist]::new                                                        
      
      OverloadDefinitions
      -------------------
      System.Collections.ArrayList new()
      System.Collections.ArrayList new(int capacity)
      System.Collections.ArrayList new(System.Collections.ICollection c)
      
      # you don't need to put [System.
      # "[Collections.ArrayList]::new(5,6,7)" didn't work
      PS /> $list = [Collections.ArrayList]::new((5,6,7)) 
      PS /> $list                                                 
      5
      6
      7
      PS /> $list.Remove(6)
      PS /> $list                                                 
      5
      7
      
  • #100267

    L-Bo
    Participant

    Use the arrays .Remove() method is the easiest. Regular arrays do not have an easy way of adding or removing objects. In order to remove an object from an array is to rebuild the array without the object.

    $array=@(2,3,5,7)
    
    $number = 7
    $array.Remove($number)
    
    "$number has been removed from `$array"
    $array
    
  • #100273

    Sam Boutros
    Participant

    Most arrays are of fixed length and the .Remove() method will not work.

    See https://superwidgets.wordpress.com/2018/01/01/practical-guide-to-powershell-arrays/ for more details

You must be logged in to reply to this topic.