Adding/Importing Synonyms of Terms in Term Store using PowerShell

We had a requirement to add new Synonyms to the Terms in Term Store. These Synonyms were based on Search keywords that end users were using to find the content.

Prerequisite:

A CSV file with two columns, first is Term & second one as Synonyms. The csv file will look like following table. (Added demo values). Multiple values can be semi colon separated. Let name this csv as ImportSynonyms.csv

Term Synonyms
MyName Deepak;Deepak Virdi;Consultant
MySkills SharePoint

The powershell script to Import these Synonyms:

<pre>if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
 Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

cls

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy")

Write-Host "Adding Synonyms to the Term Store" -foregroundcolor 'cyan'
Write-Host "__________________________________________________" -foregroundcolor 'cyan'

#Get Site
$site = Get-SPSite http://yoursiteurl

#Get CSV File
$directorypath = Split-Path $script:MyInvocation.MyCommand.Path
$termsFromExcel = Import-Csv "$directorypathImportSynonms.csv"

#Get Term Store
$session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
$termStore = $session.TermStores["Managed Metadata Service"]
$group = $termStore.Groups["MyGroup"]
$termSet = $group.TermSets["MyTermSet"];

Try
{
 ForEach ($row in $termsFromExcel){
 $termresult = $termSet.GetTerms($row.Term.Trim(), $false) 

 if( $termresult.Count -eq 1 )
 {
 $term = $termresult[0]
 $termSynonyms = $row.Synonyms.Trim().Split(";")
 
 ForEach ($synonym in $termSynonyms)
 {
 $term.CreateLabel($synonym, 1033, $false) 
 $errom = "Succeeded | " + $synonym + " added to Term: " + $row.Term
 Write-host $errom
 }
 }
 else
 {
 $errom = "Failed | Metadata Term: " + $row.Term + " not found in Term Store"
 Write-Host $errom -foregroundcolor 'red'
 }
 }
 $termStore.CommitAll()
}
Catch
{
 $errom = "Failed | " + $Error[0].Exception.Message
 Write-Host $errom -foregroundcolor 'red'
}

Write-Host "__________________________________________________" -foregroundcolor 'cyan'
Write-Host "Update completed" -foregroundcolor 'cyan' 

Don’t forget to run Full Crawl if want to see changes right away.

Leave a Reply

Your email address will not be published.