Remove a value from an array

Welcome Forums General PowerShell Q&A Remove a value from an array

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

js
 
Participant
1 month ago.

  • Author
    Posts
  • #171289

    Participant
    Topics: 3
    Replies: 3
    Points: 43
    Rank: Member

    I have a case, where I want to remove a value (at index number 2) from an array and at the same time, I am converting weblinks in the array to the file names. I am using the following code, but it is not working. What I am doing wrong?

     

     [string[]] $FilePath1 = @()
    [string] $Filepath
    for ($i=0; $i -le 534 ; $i++) {
    if($i=2) {$i++}
    $FilePath = 'C:\Test\' + $AllLinksNet[$i].Substring($AllLinksNet[$i].LastIndexOf('/')+1)
    $FilePath1 += $FilePath
    }
  • #171295

    Participant
    Topics: 9
    Replies: 423
    Points: 675
    Helping Hand
    Rank: Major Contributor

    From https://superwidgets.wordpress.com/2018/01/01/practical-guide-to-powershell-arrays/
    "To remove the 4th and 8th array elements for example regardless of their values, we use an expression similar to:
    $c = 0..($c.Length-1) | foreach { if ($PSItem -notin 3,7) { $c[$PSItem] } }
    "
    In your case, to remove the 2nd array element of the $FilePath1 array:

    $FilePath1 = 0..($FilePath1.Length-1) | foreach { if ($PSItem -ne 1) { $FilePath1[$PSItem] } }
    

    Notice that you're re-declaring the array..

  • #171304

    Participant
    Topics: 3
    Replies: 3
    Points: 43
    Rank: Member

    Thank you. It worked. But for my own knowledge, can you please point out the mistake in my code:

     [string[]] $FilePath1 = @()
    [string] $Filepath
    for ($i=0; $i -le 534 ; $i++) {
    if($i=2) {$i++}
    $FilePath = 'C:\Test\' + $AllLinksNet[$i].Substring($AllLinksNet[$i].LastIndexOf('/')+1)
    $FilePath1 += $FilePath
    }
  • #171313

    Participant
    Topics: 9
    Replies: 423
    Points: 675
    Helping Hand
    Rank: Major Contributor
    $PathList = for ($i=0; $i -le 534 ; $i++) {
        if ($i -ne 2) {
            'C:\Test\' + $AllLinksNet[$i].Substring($AllLinksNet[$i].LastIndexOf('/')+1)
        }
    }
    

    Use -eq instead of = in line 4
    Simplify code as shown

  • #171322
    js

    Participant
    Topics: 25
    Replies: 677
    Points: 1,623
    Helping Hand
    Rank: Community Hero

    It would be so easy with an arraylist.

    PS /Users/js> $a = 1,2,3
    PS /Users/js> $a = [collections.arraylist]$a
    PS /Users/js> $a.removeat(1)
    PS /Users/js> $a
    1
    3
    
  • #171685

    Participant
    Topics: 3
    Replies: 3
    Points: 43
    Rank: Member

    Thank you! Can you provide me a link where I can get more information about powershell Arraylist and how is different fro an Array. In which circumstances, which is preferable?

You must be logged in to reply to this topic.