Tuesday, October 28, 2014

Powershell script to create Managed Metadata Columns for each Term Set in a Term Store

I was writing a PowerShell script to create Managed Metadata columns in the library corresponding to each Term Set in the specified term store.
So below is the script with comments.

#This will load the SharePoint Snappin if not already loaded and also it will not throw any error if already loaded.
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin Microsoft.SharePoint.PowerShell
}

    #define SPSite and SpWeb Object
    $spSite = Get-SPSite "http://sharepoint.com"
    $spWeb = $spSite.OpenWeb("")

    #Get Taxonomy Session
    $taxonomySession = Get-SPTaxonomySession -Site $spWeb.Site
    #Get TermStore
    $termStore = $taxonomySession.TermStores["Managed Metadata Service"]
    #Get Term group corresponding to which columns would be created in the target  list
    $group = $termStore.Groups["Term Group"]
    #Get Reference to List
    $targetList=$spWeb.Lists["Target List"]
    for($i=0;$i -lt $group.TermSets.Count;$i++){
    
     #Get Current TermSet    
     $termSet = $group.TermSets[$i]
    
     #Check if another column is already present in the list.
     if(!($targetList.Fields.ContainsField($termSet.Name)))
     {
         $taxonomyField = $targetList.Fields.CreateNewField("TaxonomyFieldType", $termSet.Name)

         #Gets or sets the GUID that identifies the TermStore object, which contains the Keywords for the site that the current TaxonomyField belongs to.
         $taxonomyField.SspId = $termSet.TermStore.Id

         #Gets or sets the GUID of the TermSet object that contains the Term objects used by the current TaxonomyField object.
         $taxonomyField.TermSetId = $termSet.Id

         #if true then user can select multiple terms
         $taxonomyField.AllowMultipleValues = $true

         #group in which this field will be saved
         $taxonomyField.Group = $fieldGroup
         $taxonomyField.StaticName = $termSet.Name
         $taxonomyField.ShowInEditForm = $true
         $taxonomyField.ShowInNewForm = $true
         $taxonomyField.Hidden = $false
         $taxonomyField.Required = $false
         $targetList.Fields.Add($taxonomyField);

        
     }
    }   
    $targetList.Update(); 
    $spWeb.Dispose()
    $spSite.Dispose()
   
    Write-host “Script Completed"           

1 comment:

  1. What's up to every body, it's my first pay a visit of this webpage; this web site carries remarkable and actually good stuff for visitors.

    ReplyDelete