SharePoint content type collection cannot be modified exception in PowerShell

Got the error while scripting content type modifications with PowerShell and SharePoint 2010.

 

 

Error System.Management.Automation.MethodInvocationException: Exception calling 
"Update" with "1" argument(s): "The collection cannot be modified." ---> Microso
ft.SharePoint.SPException: The collection cannot be modified.
   at Microsoft.SharePoint.SPContentType.Update(Boolean updateChildren, Boolean
ignoreSealedOrReadOnly, Boolean throwOnSealedOrReadOnly, IList`1 exceptions)
   at Microsoft.SharePoint.SPContentType.Update(Boolean updateChildren)
   at Update(Object , Object[] )
   at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object ta
rget, Object[] arguments, MethodInformation methodInformation, Object[] original
Arguments)

AvailableContentTypes

I was using the AvailableContentTypes[$contentTypeName] to get the content type I wanted to change. But content types retrieved from this collection (as oppose to SPWeb.ContentTypes) are read-only.

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

The correct way is using the SPWeb.ContentTypes collection as the following code:

$field = $web.Fields[$fieldName]
$cType = $web.ContentTypes[$contentTypeName]
$fLink = new-object Microsoft.SharePoint.SPFieldLink $field
$cType.FieldLinks.Add($fLink)
$cType.Update($true)