December 1, 2016

// // Leave a Comment

PowerShell Script to create Bulk Site Content Types in SharePoint

1) In this post we will be creating bulk site content types in an sharepoint site by using already created site columns.

Refer the below post on how to create multiple or bulk site columns in sharepoint using powershell scripts

2) Now coming to create bulk site columns, create a CSV format of site content types information as below

Use the above csv format

3) Now use the below code to create bulk site content types at a single shot.

#This script creates site columns from the given csv file
#Author: Prem Kumar
#Date: Feb 11 2015

[string]$SiteUrl = $(Read-Host -prompt "Root Web Application Url...?"),
[string]$CsvFilePath = $(Read-Host -prompt "CSV File Path...?")

 # Create an array to store the field links to all site columns that will be added to the content type
 $fieldLinksArray = @()
#Import values from the CSV
$ctToBeAdded = import-csv $CsvFilePath 
write-host "Loaded Data from CSV file $CsvFilePath"
foreach($item in $ctToBeAdded)
    $ctToBeAddedWeb= Get-SPWeb $SiteUrl
    $parentContentType = $ctToBeAddedWeb.ContentTypes[$item.Parent]
    $ctToBeAddedCollection = $ctToBeAddedWeb.ContentTypes
    $ctToBeAddedName = $item.ContentTypeName
    $ctSiteColumns = $item.SiteColumns

    # Store all site columns in an array by splitting values at "," 
    $ctSiteColumnsArray = $ctSiteColumns.Split(",")
    foreach($siteColumn in $ctSiteColumnsArray)
        $ctSiteColumnToBeAdded = $ctToBeAddedWeb.Fields[$siteColumn]       
        if($ctSiteColumnToBeAdded -ne $null)
            $fieldLink = new-object Microsoft.SharePoint.SPFieldLink $ctSiteColumnToBeAdded
            # Add it to the field link array
            $fieldLinksArray += ,$fieldLink
        else # Site column does not exist
            write-host "The Site Column: $siteColumn to be added to content type: $ctToBeAddedName does not exist"
    # Check if the content type exists   
    write-host "Adding Content Type $item"
    if($ctToBeAddedWeb.ContentTypes[$item.ContentTypeName]-eq $null)
       # Create a new content type
        $newContentType = new-object Microsoft.SharePoint.SPContentType($parentContentType,$ctToBeAddedCollection,$ctToBeAddedName)
        $newContentType.Group = $item.Group
        $newContentType.Description = $item.Description
        [boolean]$newContentType.ReadOnly = [System.Convert]::ToBoolean($item.ReadOnly)
       foreach($link in $fieldLinksArray)

        write-host "Content Type: $item added successfully"

     $cType = $ctToBeAddedWeb.ContentTypes[$item.ContentTypeName]

       write-host "Content Type already exists: $item "
       foreach($link in $fieldLinksArray)
           write-host "Site Column $link added to contentType $cType "


    write-host "Exception in Content Types $_.Exception.Message"
    write-host "Exit of Content Types ..."


Post a Comment