In this article, you will learn how we can retrieve, create, or delete content type using CSOM with PowerShell. This is mainly focused on using PowerShell scripts for SharePoint online sites.
Retrieve Content Type:
First we will see how we can get the existing content types available on the SharePoint site. The steps followed here are very similar to the steps following CSOM or JSOM programming.
- Initialize context object with the site URL parameter. Then initialize the SP Online Credentials with the above parameters and set it to the context.
- Then access the necessary parameters using the context, load the objects and execute the query.
- Loop through the result object and get the necessary content type information,
This will get all the content type names available on the site. Next, We will see how we can create content types to the site.
Create Content Type:
Here we will see how we can create a content type on the site. The following steps depict the flow.
- Follow the first three steps from above section.
- Check if the new content type already exists using the below logic. Follow the below steps to add new content type,
- Get the parent content type using GetById method. In this case, parent content type is document.
- Initialize the ContentTypeCreationInformation object.
- Set the required parameters for new content type. The necessary parameters are name, parent content type and content type group.
- Add the content type.
- Load and execute the query.
The content type will be added at the root site collection level. You can add the columns manually or using script. Try navigating to the site content types page “/_layouts/15/mngctype.aspx”. You will now see the content type. The following data can be found on the content types page.
Delete Content Type:
Here we will see how we can delete the content type from the site. Following steps depict you the flow.
- Follow the first three steps from "Retrieve Content Type" section above.
- From the available content types, find out the id of the content type to be deleted. The following snippet helps you in identifying the id,
- Then, remove the content type using the delete object method.
- Using the context, execute the query,
- The content type will be removed from root site collection level. Try navigating to the site content types page “/_layouts/15/mngctype.aspx”. You will not see the content type.