Cannot remove item from an array

Welcome Forums General PowerShell Q&A Cannot remove item from an array

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

 
Participant
2 years ago.

  • Author
    Posts
  • #64917

    Participant
    Points: 1
    Rank: Member

    Hello,

    I try to make an array of computernames in my network to shut them down. All computers, except a few, must be shut down.

    So, I created an array of all computers and get there computername back.

    [Collections.ArrayList]$allepcs = Get-ADComputer -Filter {name -like 'wks*' -and enabled -eq 'true'} | Select-Object -ExpandProperty name
    $allepcs.count

    The result of the count is 111 here.

    Next I run an example code to exclude wks2000 from the array:

    $allepcs.Remove('wks2000')

    Expecting that it will remove the computername wks2000 from the array. The result of the count is however still 111 and a listing of the $allepcs still displays the computername.

    I get no error, it just does not remove any of the items in my array.

    Does anybody have an idea what I am doing wrong here?

  • #64921

    Participant
    Points: 1
    Rank: Member

    Hi,

    If you typed

     $allepcs.GetType().name 

    does it return 'ArrayList' ?

    Also double check its not a case-sensitive issue. I created a [collection.ArrayList] with three values of 'pc1','pc2' and 'pc3'.

    if i do $test.Remove('pc1'), it works fine. If i then try $test.Remove('PC2') i get no output to the screen still, but this time the item has not been removed from the ArrayList.

    Hope this helps.

  • #64929

    Participant
    Points: 1
    Rank: Member

    Hi Graham, you are the best.

    The problem was that it is case-sensitive. Thanks a lot.

    • #64933

      Participant
      Points: 1
      Rank: Member

      Pleasure. Always the simple things that trip us up 🙂

  • #64930

    Participant
    Points: 527
    Helping Hand
    Rank: Major Contributor

    That code works for me. I validated that the cast works and shows the object type as ArrayList. When I do a .Remove("Name") it is removed from the list

    [Collections.ArrayList]$allepcs = Get-ADComputer -Filter * | Select-Object -ExpandProperty name
    "First Count: {0}" -f $allepcs.Count
    $allepcs.Remove("RES-ENG-MNGR")
    "Second Count: {0}" -f $allepcs.Count
    $allepcs.Remove("RES-ENG-DC01")
    "Third Count: {0}" -f $allepcs.Count
    

    Output:

    First Count: 11
    Second Count: 10
    Third Count: 9
    

    You can always use the Where filter to exclude the PC's from the resultset as well.

  • #64936

    Participant
    Points: 527
    Helping Hand
    Rank: Major Contributor

    Ah, case sensitive. Another mystery solved.

The topic ‘Cannot remove item from an array’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort