Sharepoint 2010 Create Custom Site Column and Add to Content Type using Powershell

Sometimes we need to add column to existing content type. For the same there are two ways.

  • one is delete content type. If it has used some where else than first need to delete that target and after that delete this content type and create from scratch. So its a very long process. 
  • Another way is create a site column first and add that column to content type(Using Powershell) as below. It will help you for sure.


clear
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

Function AddFieldToContentType($web, $ctype, $fieldName, $DisplayName)
{
    $ct = $web.ContentTypes[$ctype]
    $fieldXMLString = '<Field Type="Text"
    Name= "'+$fieldName+'"
    DisplayName= "'+$DisplayName+'"
    Group="IPM Document Group"
    Required="FALSE"
    ShowInDisplayForm="TRUE"
    ShowInEditForm="TRUE"
    ShowInListSettings="TRUE"
    ShowInNewForm="TRUE"></Field>'
   
    $web.Fields.AddFieldAsXml($fieldXMLString) #Create Custom Site Column
    $field = $web.fields.getfield($fieldName) 
   
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ct.fieldlinks.add($fieldLink) #Add Custom Column to Content Type
$ct.update()
}

$url = "Site Collection Url"
$site = Get-SPSite($url);
$web =  $site.OpenWeb();

AddFieldToContentType $web "Content Type Name"  "Column Field Name" "Column Display Name

Comments

Popular posts from this blog

C# Copy files from one server to another

Export SharePoint Online Group Users to Excel using Powershell

Suppress StyleCop SA1600