Sunday, October 21, 2012

Mapping Taxonomy Fields with Terms using PowerShell


SalesForce Tips

Updating Taxonomy Fields with Terms using PowerShell

Being a beginner in PowerShell script I had a bit of fun trying to figure out getting around a scenario where we had to map a given term (instead of TermSets) which had sub terms to a site column value. Below was the sample hierarchy for the Taxonomy



Here Country, Language were the Groups, Finance and HumanResources were the TermSets and the remaining were Terms. We needed to map the Terms to the site columns using PowerShell script reading the data from a configurable xml.
Though there were a couple of articles mentioning how to do the mapping to TermSet values ,it did not seem to work. The main thing missing was the AnchorID property. This is the mapping used by the fields to associate it to the Term value$field.AnchorId = $term.Id )  You can see the sample script used for the mapping below. 



# Create Site object
$site = Get-SPSite "http://siteurl/"
# Get the field ref
[Microsoft.SharePoint.Taxonomy.TaxonomyField]$field = $site.RootWeb.Fields | Where-Object { $_.Name -eq "FIELDNAME" }
$session = new-object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
# Get the term store instance
$termstore = $session.TermStores["Managed Metadata Service"]
# Get the Term Group using the Name
$group = $termstore.Groups | Where-Object { $_.Name -eq "Company" }
# Get the TermSet using the TermSet name
$termSet = $group.TermSets | Where-Object { $_.Name -eq "Finance" }
$terms = $termSet.GetTerms(100)
# Get the Term using the name
$term = $terms | ?{$_.Name -eq "Country"}
# Update the SspId
$field.SspId = $termstore.Id
$field.TermSetId = $termSet.Id
# Map the term value
$field.AnchorId = $term.Id
# Update the field
$field.Update()

Hope this helps !!!