Following on from my blog a few weeks ago, I thought I’d cover creating MMS columns via PowerShell. My last blog gave examples of creating text fields, number fields, and choice fields with PowerShell. Creating Taxonomy (Managed Metadata) columns is slightly different.
The overall principle of creating an MMS column is as follows:
- Get a reference to the Term Store
- Find the Term Set
- Create a Field
- Map the Field to the Term Set
The first step is to set up your variables to be used in the script:
$fieldName = "PowerShell MMS Column"
fieldName – The name for your new MMS column
siteUrl – The site in which your new MMS column is available
mmsServiceName – The name of the MMS Service Application where the Term Set lives
mmsGroupName – The name of the Group where the Term Set lives
mmsTermSetName – The name of the Term Set which your new MMS column will reference
Then, get a reference to the Site Collection, and the Web in which you want to create the new column.
$site = Get-SPSite $siteUrl
The next line is the most important part. As defined by MSDN:
“The TaxonomySession object is the starting point for all operations involving objects from the taxonomy. It provides access to one or more TermStore objects, (for example, managed metadata connections), where the Group, TermSet, and Term objects reside.”
We need this to get references to the Managed Metadata Service Application, Group and Term Set.
$taxonomy = Get-SPTaxonomySession -Site $site
Depending on your Farm setup, this may return 1 or more objects. To be safe, I filter this using the mmsServiceName variable, and select its GUID. This GUID is used later on, to point the column to the correct service application where it can find the Term Set:
$sspId = $taxonomy.TermStores |
Now we just need a reference to our Term Set Id. To do this, first we get a reference to the Group object, and then filter down to the TermSet object. Again, we then select the GUID to point to:
$termSetId = $taxonomy.TermStores.Groups |
At this point, we’re ready to create the column. This is very similar to creating any other column. First, create the “TaxonomyFieldType” field, and add it to the web. Then, update the TermSetId property, and the SspId property to link it to the Term Set. You could also update other properties here, such as the columns group, and whether it’s required or not.
$field = $web.Fields.CreateNewField("TaxonomyFieldType",$fieldName)
And that’s all there is to creating an MMS column. You can download the full commented script here.