Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this powershell for loop stops after 4 iteration

I know I have to delete 8 lists (custom list and library). The following only deletes 4, then I have to execute again and it deletes 2, then 1 and then 1. Any idea why?

$site = "http://inside.comp.com/sales"
$featureID = "b432665a-07a6-4cc7-a687-3e1e03e92b9f"
$str = "ArcGIS"
Disable-SPFeature $featureID -Url $site -Confirm:$False
start-sleep -seconds 5
$site = get-spsite $site
foreach($SPweb in $site.AllWebs)
{   
    for($i = 0; $i -lt $SPweb.Lists.Count; $i++)
    {
        $spList = $SPweb.Lists[$i]
        if($SPList.Title.Contains($str))    
        { 
            write-host "Deleting " $SPList.Title -foregroundcolor "magenta"
            $spList.Delete()            
            #$SPweb.Update()
        }
    }
    $SPweb.Update()
}
like image 575
user1497590 Avatar asked Mar 25 '26 01:03

user1497590


1 Answers

It is because when you delete an item 0 in a list, the list item 1 becomes 0, and it is skipped on this run. Then the same thing is repeated another 3 times, where only 3 items are removed.

In order to fix this iterate items from the back:

for($i = $SPweb.Lists.Count - 1; $i -ge 0; $i--)
{
    # The rest of the cycle
}
like image 146
dotnetom Avatar answered Mar 26 '26 17:03

dotnetom