Change MMS Field Term Set using CSOM and PowerShell

The script below allows you to change Term Set ID to a Column in SharePoint Online using Client Side Object Model.  One of my client used an MMS Field in multiple libraries without using Site Column so I had to write this script to change the ID.  You can change the script to do it on all the sites and sub sites.  You must use latest CSOM Components from Github for better performance.

$Creds = Get-Credential

Connect-PnPOnline -Url https://sharepointmvp-Admin.sharepoint.com -Credential $Creds

Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll”
Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll”
Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll”

$site = https://tenant.sharepoint.com
#Get the Client Context and Bind the Site Collection
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($site)

#Authenticate
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Creds.UserName , $Creds.Password)
$ctx.Credentials = $credentials

#Fetch the users in Site Collection

$ListTitle = “Documents”
$FieldTitle = “Description”

$Web = $ctx.Site.RootWeb
$ctx.Load($Web)
$DocLib = $Web.Lists.GetByTitle($ListTitle)
$ctx.Load($DocLib)

$Fields = $DocLib.Fields
$ctx.Load($Fields)
$ctx.ExecuteQuery()
$PrimaryTag = $Fields | Where {$_.InternalName -eq “TermRenameTest1”}

$taxStore = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($ctx) 
$ctx.Load($taxStore) 
$ctx.ExecuteQuery() 

$termStore = $taxStore.TermStores.GetByName(“Taxonomy_nWOs0zXx5ZUobXtn3QOy+A==”)
$Groups = $termStore.Groups 
$ctx.Load($termStore) 
$ctx.Load($Groups) 
$ctx.ExecuteQuery() 

$Group = $Groups.GetByName(“HR Group”) 
$termSet = $Group.TermSets.GetByName(“New”) 
$ctx.Load($termSet) 
$ctx.ExecuteQuery() 

if($PrimaryTag)
{
  $field = [Microsoft.SharePoint.Client.ClientContext].GetMethod(“CastTo”).MakeGenericMethod([Microsoft.SharePoint.Client.Taxonomy.TaxonomyField]).Invoke($ctx, $PrimaryTag)
  $field.SspId = $termStore.Id
  $field.TermSetId = $termSet.Id
  $field.Update()
  $ctx.ExecuteQuery()
}

$ctx.ExecuteQuery()

Update: Script is also available

https://gallery.technet.microsoft.com/Change-MMS-Field-Term-Set-efdf705f

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