Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Within a PS script, I'm trying to add a site column and add this column to a custom content type.

Here is my script :

add-pssnapin Microsoft.SharePoint.PowerShell -EA 0

function AddFieldToContentType([Microsoft.SharePoint.SPWeb] $web, [string]$contentTypeName, [string]$xmlSchema)
{

    $fieldName = $web.Fields.AddFieldAsXml($xmlSchema)
    $web.Update()

    $field = $web.Fields[$fieldName]
    $ct = $web.AvailableContentTypes[$contentTypeName]
    $link = new-object Microsoft.SharePoint.SPFieldLink $field
    $ct.FieldLinks.Add($link)
    $ct.Update($true)


}

[Microsoft.SharePoint.SPWeb]$web = get-spweb -Identity http://somewhere
[xml]$xml = 'my field schema truncated for readability'

AddFieldToContentType $web "my content type name" $xml

This fails at the line $ct.Update($true) with this error :

Exception calling "Update" with "1" argument(s): "The collection cannot be modified."

What's wrong with this code ?

Thanks

share|improve this question

1 Answer 1

up vote 6 down vote accepted

AvailableContentTypes is readonly, so you need to use ContentTypes instead.

$field = $web.Fields[$fieldName]
$ct = $web.ContentTypes[$contentTypeName]
$link = new-object Microsoft.SharePoint.SPFieldLink $field
$ct.FieldLinks.Add($link)
$ct.Update($true)
share|improve this answer
    
To add to this, AvailableContentTypes is read only because it is a collection from the current scope, including those of the current website, as well as any parent websites –  Tim Gabrhel Jul 6 '11 at 16:09
    
this solved the problem, hovewer, I don't understand the cause, as I'm not changing the content type collection, but the content type itself –  Steve B Jul 6 '11 at 16:29
    
The Update() method must be looking at the collection that the content type is in and using that in some way. It follows since you can't create a new content type and call Update() without first adding it to a collection - a list or web. AvailableContentTypes gathers them up into a collection for you, but it doesn't give you the collection for the specific web. –  Laurie Jul 6 '11 at 16:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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