August 17, 2016

Add Site Column to multiple Content Types using PowerShell

Scenario
In large SharePoint Environment, we have hundreds of Site Content Types in site collection. And the requirement was to add new site column to all site content types of specific group.

Approach
Yes, first thing comes to mind is, lets add it to content type one by one through GUI. But it is not feasible approach while dealing with hundreds of content types as it becomes very tedious task.

So, I have decided to implement PowerShell script through which it can be added to all content types of specific group at once.

Code:

$site = Get-SPSite "<Site Collection Url>"
$web = $site.RootWeb

foreach ($ctype in $web.ContentTypes)
{
    if($ctype.Group -eq "<Site Content Type Group Name>")
    {     
        foreach($field in $web.Fields)
        {
            if($field.Group -eq "<Site Column Group Name>")
            {
                if($field.Title -eq "<Site Column Name>")
                {
                    if($ctype.Fields.ContainsField($field) -eq $false)
                    {
                        $link = new-object Microsoft.SharePoint.SPFieldLink $field
                        $ctype.FieldLinks.Add($link)
                        $ctype.Update($true)
                    }
                }
            }
        }      
    }
}

That's it, Done!!!


If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment