Array question

Welcome Forums General PowerShell Q&A Array question

This topic contains 4 replies, has 4 voices, and was last updated by

js
 
Participant
6 months, 2 weeks ago.

  • Author
    Posts
  • #100264

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    Oopss,

    Final result like

    Column1
    ——–
    0
    0
    3
    7

    • #100297
      js

      Participant
      Points: 219
      Helping Hand
      Rank: 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

    Participant
    Points: 58
    Rank: Member

    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

    Participant
    Points: 60
    Rank: Member

    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

The topic ‘Array question’ is closed to new replies.