SharePoint Pals
 | Sign In
How to create SiteColumns and Add them to Content Types Using PowerShell in SharePoint 2013
by Sathish Nadarajan 23 Dec 2014
Author
SharePoint MVP
Visits   
Today  :   18     Total  :    17421

In Many situations, we would have faced this problem. i.e., the Schema definition for our Project. The SiteColumns and the Content Types. If we freeze these two things, then our project execution will become smooth. The struggle people face on this is like, we will be creating the site columns and the content types through Element.xml and on the Feature activation, and we will provision these site columns and the content types. Later when we need to add some more columns or modifying any existing columns, the Feature which we already created may not be helpful, as it will not retract all the site columns already created unless we had a separate feature receiver for this cleanup activity. And moreover when we do a cleanup, the data loss would happen.

To avoid this, and make this process a little bit easier, creating the PowerShell can be done using PowerShell. In this article, let us how to do that.

In this demo, let me create 3 site columns. One with the Taxonomy field, because this column requires a Mapping of term, second one is a simple Text field and a choice field. As these are the columns which we will using frequently, I am taking this.

Let us have these things as a CSV.

Please refer the attached CSV.

The Script is self-explanatory

 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 
 $LogFile = ".\CreateSiteColumnReferencePatch-$LogTime.rtf"
 
 cls
 
 #start-transcript $logfile
 
 ######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) 
 
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }
 
 ########################### End of Add SharePoint PowerShell Snapin ##################################
 
 ######################## Set Execution Path ################################################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 
 Set-Location $scriptBase
 
 ################################# End of Set Execution Path #################################
 
 ################################# Functions #####################################################
 
 Function CreateField ([string]$siteUrl, [string]$fieldXML, [string] $centralADminURL,[string] $TermStoreName, [string] $TermGroupName, [string] $TermSetName,[string] $FieldinternalName,[string] $Type) 
 
 {
 
 $site = Get-SPSite -Identity $siteUrl
 
 $web = $site.RootWeb 
 
 write-host "Creting Site Column with following details " $fieldXML -fore yellow
 
 $web.Fields.AddFieldAsXml($fieldXML) 
 
 write-host "Site Column with details " $fieldXML " created successfully ........... Done !" -fore green
 
 if($Type -eq "TaxonomyFieldType")
 
 {
 
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy")
 
 $site = Get-SPSite $centralADminURL
 
 $session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
 
 $termStore = $session.TermStores[$TermStoreName]
 
 $group = $termStore.Groups[$TermGroupName]
 
 $termSet = $group.TermSets[$TermSetName]
 
 $column = $web.fields.getfieldbyinternalname($FieldinternalName)
 
 if($Column)
 
 {
 
 $column.sspid = $termstore.id
 
 $column.termsetid = $termSet.id
 
 $column.update($true);
 
 }
 
 }
 
 $web.Dispose()
 
 $site.Dispose()
 
 }
 
 function AddSiteColumnsToContentTypes([string]$siteUrl, [string]$fieldName, [string]$contentTypeName) 
 
 {
 
 $site = Get-SPSite $siteUrl
 
 $web = $site.RootWeb
 
 $field = $web.Fields.getfieldbyinternalname($fieldName)
 
 $ct = $web.ContentTypes[$contentTypeName]
 
 $link = new-object Microsoft.SharePoint.SPFieldLink $field
 
 write-host "Adding site column " $fieldName " to content type " $ct.name -fore yellow
 
 $ct.FieldLinks.Add($link)
 
 write-host "Site column " $fieldName " is added to content type " $ct.name " Successfully ...... Done !"-fore green
 
 $ct.Update($true)
 
 }
 
 ################### End of Functions ###############################################
 
 #################Creating Site columns##########################################################
 
 $SiteColumnCreationDetailsCSV = $scriptBase + "\" + "05.SiteColumnCreationDetails.csv"
 
 import-csv $SiteColumnCreationDetailsCSV | where {
 
 CreateField $_.siteurl $_.FieldXML $_.centralADminURL $_.TermStoreName $_.TermGroupName $_.TermSetName $_.FieldinternalName $_.Type
 
 }
 
 #################Adding site column to content type#############################################
 
 $SiteColumnReferencedContentTypesCSV = $scriptBase + "\" + "06.SiteColumnReferencedContentTypes.csv"
 
 import-csv $SiteColumnReferencedContentTypesCSV | where {
 
 AddSiteColumnsToContentTypes $_.SiteURL $_.FieldName $_.ContentTypeName
 
 }
 
 #stop-transcript 
 

On the CSV File, we have a column called FieldXML. People may think, how to get that XML. Even that also made easy, if we use the SharePoint Manager.

The simple idea is, create a test column on the Site Manually. Using the SharePoint Manager, get the Schea XML. Replace on the CSV file. Execute the PS1. Very simple right. Hope this will be helpful for many developers, admins to eliminate the problems with the Schema.

 

Download Script HERE

 

Happy Coding.

Sathish Nadarajan.

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation