4

I need to delete all libraries from a subsite, however I got this error:

Collection was modified; enumeration operation may not execute



$web = Get-SPweb($webUrl)


  foreach($list in $web.Lists) {
    if($list.BaseType -eq "DocumentLibrary")
    {
        write-host $list.BaseType
       $list.Delete

    }
  }

2 Answers 2

12

You get this error because you're deleting straight from your source collection, which will change as soon as you start deleting.

A possible solution is to first get all the lists you wish to delete and store them in a seperate list (not subject to modification, since this is not the source collection)

$listsToDelete = @()

foreach($list in $web.Lists) {
    if($list.BaseType -eq "DocumentLibrary")
    {
        $listsToDelete += $web.Lists[$list.Title]
    }
}

foreach($listToDelete in $listsToDelete) {
    $listToDelete.Delete()
}
2
  • 1
    saved me a few hours... Commented Feb 13, 2015 at 17:12
  • This saved my bacon a while back. Then I forgot this solution. It's just saved my bacon again! haha :)
    – user43832
    Commented May 30, 2019 at 14:04
2

Below also works

$web = Get-SPweb($webUrl)
  foreach($i in (0..($web.Lists.length-1))){
    if($web.Lists[$i].BaseType -eq "DocumentLibrary"){
        write-host $web.Lists[$i].BaseType
       $web.Lists[$i].Delete
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.