11

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

20

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)
  • 1
    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
  • I get almost this exact same problem: - $ct.update($true) produces an "Access Denied" error, although it does add the Site Column to the Content Type. - however, $ct.update($false) works without a hitch. - not only that, but in both cases, the "update all columns which use this column" is set to Yes. I've no idea why it acts this way. – Josh Korn Nov 3 '16 at 15:29

protected by Community May 23 '16 at 7:40

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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