3

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

    }
  }
10

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()
}
  • 1
    saved me a few hours... – Luis Valencia Feb 13 '15 at 17:12
  • This saved my bacon a while back. Then I forgot this solution. It's just saved my bacon again! haha :) – Nullldata May 30 at 14:04
1

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, privacy policy and cookie policy

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