Share via

Removing Objects from an Array during a Foreach

Kevin T 21 Reputation points
2021-09-07T12:06:11.343+00:00

Hi all I am trying to remove $BPVM from $BPVMS array if a condition is false, after the line $completed--. The idea is to keep checking a computer to see if an application is installed, if its not it will wind down a list to 0, once the count is zero the do loop terminates. I am unable to achieve the desired reults. I have tried filtering the array and then using % {$_.delete() but that doesnt work. It errors. Unless there is a better way of doing this? Please help

 $Completed = $BPVMs.count


 do {

    Foreach ($BPVM in $BPVMs) {


        Write-Host -ForegroundColor cyan "Checking for Blue Prism Installation on" $BPVM.name 

        if (Get-CimInstance -ComputerName $BPVM.name win32_product | Where-Object {$_.name -eq "Blue Prism"} | Select Name){

        Write-Host -ForegroundColor green "True"

        }Else{

         Write-Host -ForegroundColor Red "False"

         $Completed--

        }

        Write-Host -ForegroundColor red "There are" $Completed "VMS remaining"
    }

  }Until ($Completed -eq 0)
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

2 answers

Sort by: Most helpful
  1. Limitless Technology 40,101 Reputation points
    2021-09-14T12:32:17.49+00:00

    Hi @Kevin T

    I think you can spread an array inside of an array, in order to keep items array clean, when the condition is false.

    If an Answer is helpful, please click "Accept Answer" and upvote it : )

    Was this answer helpful?

    0 comments No comments

  2. Rich Matheisen 48,116 Reputation points
    2021-09-07T14:48:55.233+00:00

    The problem is that you can't modify the array while it's being used as the control for ending the ForEach loop. Doing so would screw up the cursor and eventually lead to your trying to access elements of the array that no longer exist. This is because the ForEach evaluates the size array only once -- at the beginning.

    It's probably easiest to build a new array -- based on the POSITIVE test -- and then replace the $BPVMs array with the new array.

    You CAN modify the existing array, but it would mean that you'd have to maintain the cursor and also adjust the ending condition based on the new size of the array.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.