Create Managed Metadata Column using Power Shell

Although creating a managed metadata column is pretty straight forward using a web browser. But sometimes we need to automate things, if we need to create bulk of columns.

Here is a code snippet to achieve this.

$siteUrl = “http://somesharepointweb”;
$fieldName = “Region”;
$fieldGroup = “Custom”;
$allowMultipleValues = “false”;
$isRequired = “true”;
$termStoreName = “Managed Metadata Service”;
$termGroupName = “Intranet”;
$termSetName = “North America”

#Get sp web
$site = New-Object -TypeName “Microsoft.SharePoint.SPSite” -ArgumentList $siteUrl;

$fieldType = “”;
$bAllowMulitpleValues = “”;
$bIsRequired = “”;

if ($allowMultipleValues.ToLower() -eq “true”)
{
$fieldType = “TaxonomyFieldTypeMulti”
}
else
{
$fieldType = “TaxonomyFieldType”
}
if ($allowMultipleValues.ToLower() -eq “true”)
{
$bAllowMulitpleValues = $true;
}
else
{
$bAllowMulitpleValues = $false;
}

if ($isRequired.ToLower() -eq “true”)
{
$bIsRequired = $true;
}
else
{
$bIsRequired = $false;
}

#Create a taxonomy field
$field = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$site.RootWeb.Fields.CreateNewField($fieldType, $fieldName);

#Get a taxonomy session
$session = new-object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)

#Get Term Store
$termstore = $session.TermStores[$termStoreName]

#Get Term Group
$group = $termstore.Groups[$termGroupName]

#Get Term Set
$termSet= $group.TermSets[$termSetName]

#populate newly created field
$field.Sspid = $termSet.TermStore.Id
$field.TermSetId = $termSet.Id
$field.AllowMultipleValues = $bAllowMulitpleValues
$field.Group = $fieldGroup
$field.Required = $bIsRequired
$site.RootWeb.Fields.Add($field)

#Update sp web
$site.RootWeb.Update()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: