I am having problems trying to loop through and remove 91 components from my COM+ Application
This is my Powershell code:
$app = $apps | Where-Object {$_.Name -eq 'pkgAdap2'}
$compColl = $apps.GetCollection("Components", $app.Key)
$compColl.Populate()
$index = 0
foreach($component in $compColl) {
$compColl.Remove($index)
$compColl.SaveChanges()
$index++
}
The code appears to work but it only removes HALF of the components and for the rest of the $index
the loop returns this error:
Value does not fall within the expected range.
At line:4 char:5
+ $compColl.Remove($index)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
So I keep running it and the number of components left keeps getting reduced by half.
I think the reason is that the array/collection I am "removing" from re-sorts the remaining indexes, moving them over every time. So I only get through half before $index
is out of range. It is the only thing I can figure is doing this. Thus I also tried another approach:
while($compColl.Count > 0) {
$compColl.Remove($compColl.Count)
}
But it doesn't work either.
Does anyone know how to delete all components at once?
It sounds like the indices of your collection are 0
-based, so the following should work:
while($compColl.Count -gt 0) {
$compColl.Remove($compColl.Count - 1) # remove last element, which updates .Count. Using 0 to remove the first one is a good option to.
}
$compColl.SaveChanges()
If you're sure that the collection won't change while you're enumerating it, this variant is probably slightly more efficient:
for ($i = $compColl.Count - 1; $i -ge 0; --$i) {
$compColl.Remove($i)
}
$compColl.SaveChanges()
The problem with your original approach was that every $compColl.Remove($index)
call implicitly decremented the indices of the remaining items, so that $index++
ended up skipping items until it reached a value beyond the remaining highest index and failed.
Generally, it's problematic to loop over a collection item by item while modifying that collection in the loop body.