CSOM PowerShell – add a field to a list content type

Some people will read the title of this blog post and wonder why I’m writing this when there are plenty of samples to do this online. Some of them written a long time ago. It covers a common requirement: add a SharePoint field to a list content type.

But the reason is simple: I wasn’t able to find a single one that worked on a reliable way.

The following did the trick for me when adding a field to a list content type:

// code to load objects and create a new FieldLinkCreationInformation object)

$add = $contentType.FieldLinks.Add($fieldLinkCreationInformation)

// code to update the content type)

The important part to note, and the difference from most samples available online, is the “$add =“. This is required when adding the FieldLinkCreationInformation object to the FieldLinks collection. Without assigning the operation to a variable, the instruction may fail with the error message:

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

This falls in line with some other CSOM operations that now require this approach. If you see the previous error message when using CSOM and are sure that you are explicitly requesting all the properties, look for operations similar to the one above and try assigning the operation to a variable.

I won’t get back the hours I’ve wasted trying to find the solution to it but hopefully can save you some time in the future.

Leave a Reply

Your email address will not be published. Required fields are marked *