0

I am using below script to iterate through each document library and create a column with the value equals to the name of library itself:

   $ver = $host | select version 

if($Ver.version.major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"} 

if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0)) 

{ 

Write-Progress -Activity "Loading Modules" -Status "Loading Microsoft.SharePoint.PowerShell" 

Add-PSSnapin Microsoft.SharePoint.PowerShell 

} 





$SourceWebURL = "http://sitecollection/sites/sitename" 





$ssite = Get-SPSite $SourceWebURL

$sweb = $ssite.OpenWeb("Op")



foreach($slist in $sweb.Lists) 

{

    if($slist.BaseType -eq "DocumentLibrary")

            {

                        $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text

                        $sList.Fields.Add("OpCo",$spFieldType,$true)

                        $field = $sList.Fields["OpCoName"]

                        $field.DefaultValue = $slist.Title

                        $field.Update()

                        $sList.Update()

            }

}

I am getting below error:

An error occurred while enumerating through a collection: Collection was modifi
ed; enumeration operation may not execute..
At C:\Users\abc.ps1:31 char:8
+ foreach <<<< ($slist in $sweb.Lists)
    + CategoryInfo          : InvalidOperation: (Microsoft.Share...on+SPEnumer
   ator:SPEnumerator) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration
  • What do you mean with assign a value? Your code is only adding the field to the list. You can not add a value to the field itself, you need to add values to individual list items. Or do you want to set a default-value? – Robert Lindgren Mar 18 '15 at 8:18
  • I want to add value to newly created column. Its a default value for a particular library equals to library name itself – Aquarius24 Mar 18 '15 at 8:21
  • 1
  • I have modified the code – Aquarius24 Mar 18 '15 at 9:49
1

The error you are getting seems to be related to processing the collection rather than setting the default value. You should investigate a better way to get your lists that won't modify the collection as you process it. Here is a rough example:

$ssite = Get-SPSite $SourceWebURL

$sweb = $ssite.OpenWeb("Op")

#Get the URLs for the lists we want to process
$listUrls = $sweb.Lists | Where-Object { $_.BaseType -eq "DocumentLibrary"} | Select DefaultViewURL

foreach($listURL in $listUrls) 

{
    #Get instance of the list, not associated with a collection
    $sList = $sweb.GetList($listURL)
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text

    $sList.Fields.Add("OpCo",$spFieldType,$true)

    $field = $sList.Fields["OpCoName"]

    $field.DefaultValue = $slist.Title

    $field.Update()

    $sList.Update()           

}

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.