I am running the following code to add a content type to any library that already has a particular CT. The CT I want to add is defined in the "clients" subsite and it is only doc libraries within this site that will have the "CT Looked For" CT already (because it is defined at this "clients" subsite as well).
#Get site object and
#specify name of the content type to look for in each library
$site = Get-SPSite (url)
$subsite = Get-SPWeb (url)/clients
$lookForCT = "CT Looked For"
$ctToAdd = $subsite.ContentTypes["CT to Add"]
#Walk through each site in the site collection
$site | Get-SPWeb -Limit all | ForEach-Object {
write-host "Checking site:"$_.Title
#Go through each document library in the site
$_.Lists | where { $_.BaseTemplate -eq "DocumentLibrary" } | ForEach-Object {
write-host "Checking list:"$_.Title
#Check to see if the library contains the content type specified
#at the start of the script
if (($_.ContentTypes | where { $_.Name -eq $lookForCT }) -eq $null)
{
write-host "No content type exists with the name" $lookForCT "on list" $_.Title
}
else
{
#Add site content types to the list
$ct = $_.ContentTypes.Add($ctToAdd)
write-host "Content type" $ct.Name "added to list" $_.Title
write-host "+++++++++++++++++++++++++++++"
#$ctToAdd = $site.RootWeb.ContentTypes["IT Document"]
#$ct = $_.ContentTypes.Add($ctToAdd)
#write-host "Content type" $ct.Name "added to list" $_.Title
#$_.Update()
}
}
}
#Dispose of the site object
$site.Dispose()
The code finds the first library and adds the "CT to Add" content type but then errors with:
An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not
execute..
...
$_.Lists | where { $_.BaseTemplate -eq "DocumentLibrary" } | ForEach-Object ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Share...on+SPEnumerator:SPEnumerator) [], RuntimeExcepti
on
+ FullyQualifiedErrorId : BadEnumeration
Any guidance would be appreciated.
Guidance on how to limit the loop to look only inside of the "clients" subsite would also be appreciated.
Thanks.