Office 365 - How to create content type in SharePoint Online using PowerShell?

Create content type in SharePoint Online using PnP PowerShell

2 comments

Loading

In this “Create content type in SharePoint Online” tutorial, we will learn about how to create a content type in SharePoint Online using PnP PowerShell.

Key-Highlights: Create content type in SharePoint Online

  • What is the content type in SharePoint Online?
  • What is the use of a content type in SharePoint Online?
  • How to create a content type in SharePoint Online using PowerShell?
  • Verify that the content type created by PowerShell is available on the site
  • How to create a content type in SharePoint Online using the PnP PowerShell?
  • Verify that the content type created by PnP PowerShell available on the site
  • How to add a content type to the SharePoint list/library using the PnP PowerShell?

What is the content type in SharePoint Online?

A content type is a reusable collection of metadata (columns), workflow, behavior, and other settings for a category of items or documents in a Microsoft SharePoint Foundation 2010 list or document library. Content types enable you to manage the settings for a category of information in a centralized, reusable way.

What is the use of a content type in SharePoint Online?

As we know a content type in SharePoint is a reusable set of metadata, the need or uses of the content type in business are huge.

For example, imagine a business situation in which you have three different types of documents: Sales Reports, Purchase Reports, and invoice Reports. All three types of documents have some characteristics in common; for one thing, they are all financial documents and contain data with values in currency. Yet each type of document has its own data requirements, its own document template, and its own workflow.

One solution to this business problem is to create four content types. The first content type, Financial Document, could encapsulate data requirements that are common to all financial documents in the organization. The remaining three, Sales Report, Purchase Report, and Invoice Report could inherit common elements from the Financial Document. In addition, they could define characteristics that are unique to each type, such as a particular set of metadata, a document template to be used in creating a new item, and a specific workflow for processing an item.

You can use each of the content types in this example on any document library in the site hierarchy, and you can use all of them together on the same document library. When business requirements change, you can modify the content types to meet the new requirements and push down the updates to any document library where the content type is used.

How to create a content type in SharePoint Online using PowerShell?

Using the below PowerShell script, we can create a content type in SharePoint Online.


#The below script will create a Content Type in SharePoint online using PowerShell and PnP PowerShell which will take site URL, document library name, UserName and Password as paramaters.
#Load SharePoint CSOM Assemblies
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
cls

$fileName = "Create_ContentType_Report"
#'yyyyMMddhhmm yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename = $enddate + '_VMReport.doc'
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"
$invocation = (Get-Variable MyInvocation).Value
$directoryPath = Split-Path $invocation.MyCommand.Path

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))
{
New-Item -ItemType directory -Path $directoryPathForLog
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
#$logPath = $directoryPath + "\" + $logFileName

$logPath = $directoryPathForLog + "\" + $logFileName

$isLogFileCreated = $False

#DLL location

$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))
{
New-Item -ItemType directory -Path $directoryPathForDLL
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}

#DLL location
$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime
#File Download location

$directoryPathForFileDownloadLocation=$directoryPath+"\"+"Downloaded Files"
if(!(Test-Path -path $directoryPathForFileDownloadLocation))
{
New-Item -ItemType directory -Path $directoryPathForFileDownloadLocation
#Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}

#File Download location

function Write-Log([string]$logMsg)
{
if(!$isLogFileCreated){
Write-Host "Creating Log File..."
if(!(Test-Path -path $directoryPath))
{
Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
}
else
{
$script:isLogFileCreated = $True
Write-Host "Log File ($logFileName) Created..."
[string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
Add-Content -Path $logPath -Value $logMessage
}
}
else
{
[string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
Add-Content -Path $logPath -Value $logMessage
}
}

#The below function will create a content type in SharePoint Online which will take siteURL, ContentTypeName,ContentTypeyDescription, ParentContentTypeName, ContentTypeGroup,UserName and Password as paramaters.
Function CreateContentTypeInSPO()
{
param
(
[Parameter(Mandatory=$true)] [string] $SPOSiteURL,
[Parameter(Mandatory=$true)] [string] $ContentTypeName,
[Parameter(Mandatory=$false)][string] $ContentTypeyDescription,
[Parameter(Mandatory=$true)] [string] $ContentTypeGroup,
[Parameter(Mandatory=$true)] [string] $ParentContentTypeName,
[Parameter(Mandatory=$true)] [string] $UserName,
[Parameter(Mandatory=$true)] [string] $Password
)

Try
{

$securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force
#Setting up the Context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)
#Getting all content types from the site collection
$ContentTypeCollection = $ctx.web.ContentTypes
$ctx.Load($ContentTypeCollection)
$ctx.ExecuteQuery()

#Getting the parent content type
$ParentCTypeName = $ContentTypeCollection| Where {$_.Name -eq $ParentContentTypeName}

#Check if content type exists already
$ContentTypeToCreate = $ContentTypeCollection| Where {$_.Name -eq $ContentTypeName}

#Before creating a content type, check whether the content type exists or not, if not create a new one.
If($ContentTypeToCreate -ne $Null)
{
Write-host "Content type '$ContentTypeName' already exists!" -ForegroundColor Yellow
}
else
{
#List of properties for the new content type.
$ContentTypeCreationInfo=New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation
$ContentTypeCreationInfo.Name=$ContentTypeName
$ContentTypeCreationInfo.Description=$ContentTypeyDescription
$ContentTypeCreationInfo.Group=$ContentTypeGroup
$ContentTypeCreationInfo.ParentContentType=$ParentCTypeName

#Adding the new content type to the collecction.
$ContentType=$ContentTypeCollection.Add($ContentTypeCreationInfo)
$ctx.ExecuteQuery()

Write-host "The content Type '$ContentTypeName' has been created successfully!" -ForegroundColor Green

}
}
Catch
{

$ErrorMessage = $_.Exception.Message +"in creating Content Type in SPO!:"
Write-Host $ErrorMessage -BackgroundColor Red
Write-Log $ErrorMessage

}

}
#############Testing the CreateContentTypeInSPO function ############################################################

#Parameters value
$siteURL="https://globalsharepoint2020.sharepoint.com/sites/CustomSearchRND"
$ContentTypeNameToCreate="CT Created by PowerShell"
$ContentTypeNameToCreateDescription="This is a test content type"
$ParentCTypeName="Item"
$CTypeGroup="Finance Test Group"
$userName = "Global-sharepoint2020@globalsharepoint2020.onmicrosoft.com"
$passWord = "YourSPOPassword"
#Parameters ends here.
#Calling the CreateContentTypeInSPO function and passing the parameters.

#CreateContentTypeInSPO $siteURL $ContentTypeNameToCreate $ContentTypeNameToCreateDescription $CTypeGroup $ParentCTypeName $userName $passWord

#############Testing the CreateContentTypeInSPO function ends here ###################################################

Execute the above script then verify it from the site settings page.

Verify that the content type created by PowerShell is available on the site

Go to the manage content type page from the site settings navigation, then we can see that the newly created content type “CT Created by PowerShell” is available in the site.

Create content type in SharePoint Online using PowerShell Script
Create content type in SharePoint Online using PowerShell Script

How to create content type in SharePoint Online using the PnP PowerShell?

Using the below PnP PowerShell script, we can create a content type in SharePoint Online.


#############Creating a content type in SharePoint online using PnP PowerShell #######################################

CLS
$siteURL="https://globalsharepoint2020.sharepoint.com/sites/CustomSearchRND/"
$ContentTypeNameToCreate="CT Created by PnP"
$ContentTypeNameToCreateDescription="This is a test content type"
$ParentCTypeName="Item"
$CTypeGroup="Finance Test Group"
$userName = "Global-sharepoint2020@globalsharepoint2020.onmicrosoft.com"
$passWord = "YourSPOPassword"
$encPassWord = convertto-securestring -String $passWord -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $userName, $encPassWord

Connect-PnPOnline -Url $siteURL -Credentials $cred
#Getting the Parent content type using the Get-PnPContentType PnP command.
$ParentContentType = Get-PnPContentType -Identity $ParentCTypeName

#Create a Content Type using the Add-PnPContentType PnP command.
Add-PnPContentType -Name $ContentTypeNameToCreate -Description $ContentTypeNameToCreateDescription -Group $CTypeGroup -ParentContentType $ParentContentType

Write-host "The content Type '$ContentTypeNameToCreate' has been created successfully!" -ForegroundColor Green

#############Creating a content type in SharePoint online using PnP PowerShell ends here ###########################

Execute the above PnP PowerShell script then verify it from the site settings page.

Verify that the content type created by PnP PowerShell available on the site

Go to the manage content type page from the site settings navigation, then we can see that the newly created content type “CT Created by PnP” is available in the site.

Create content type in SharePoint Online using PnP PowerShell
Create content type in SharePoint Online using PnP PowerShell

How to add a content type to the SharePoint list/library using the PnP PowerShell?

Using the below PnP Powershell we can add a content type to the SharePoint list:


Add-PnPContentTypeToList -List "Documents" -ContentType "CT Created by PnP" -DefaultContentType

Reference:

https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ms472236(v=office.14)

Summary: what do we have here (Create content type in SharePoint Online)?

Thus in this article, we have learned the below with respect to content type creation in SharePoint online:

  • What is the content type in SharePoint Online?
  • What is the use of a content type in SharePoint Online?
  • How to create a content type in SharePoint Online using PowerShell?
  • How to create a content type in SharePoint Online using the PnP PowerShell?
  • How to add a content type to the SharePoint list/library using the PnP PowerShell?

See Also:

You may also like the following SharePoint PowerShell tutorials:

Download SharePoint Online PDF Book

Download SharePoint Online & Office 365 Administration eBook

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:



Buy SharePoint Online & Office 365 Administration eBook


 

Get the free demo PDF eBook from here:

FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.

 

About Post Author

2 comments on “Create content type in SharePoint Online using PnP PowerShell”

Do you have a better solution or question on this topic? Please leave a comment