question

kevint1985 avatar image
0 Votes"
kevint1985 asked MotoX80 commented

Removing Objects from an Array during a Foreach

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-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered MotoX80 commented

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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Just some awesome answers on this thread.

0 Votes 0 ·
LimitlessTechnology-2700 avatar image
0 Votes"
LimitlessTechnology-2700 answered

Hi @kevint1985

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 : )

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.