Ever needed to replace or add keywords to documents in a SharePoint site?
Recently I was in charge of migrating site collections from a on-premise environment to SharePoint online.
After the migration we needed to replace a certain taxonomy keyword on all documents. So I created a small PowerShell function to facilitate the company to do so. The function takes 5 parameters:
- Url
- URL to the site collection.
- Credential
- Credentials to contact the site collection.
- TermGuid
- The guid of the keyword that you want to find.
- AddTermGuid
- The guid of the new keyword you want to add/replace.
- Replace (switch)
- If this switch is set, it will substitute TermGuid with AddTermGuid
In order for the function to work you need to download the SharePoint PnP cmdlets here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#Replace SharePoint keywords. Function Add-SPTaxKeyword { [cmdletbinding()] Param ( [Parameter(Mandatory=$true)][string]$Url, [Parameter(Mandatory=$true)][PSCredential]$Credential, [Parameter(Mandatory=$true)][string]$TermGuid, [Parameter(Mandatory=$true)][string]$AddTermGuid, [Parameter(Mandatory=$false)][switch]$Replace ) #Connect to SharePoint site. Connect-PnPOnline -Url $Url -Credentials $Credential; #Get all libraries/list. $Lists = Get-PnPList; #Foreach list. Foreach($List in $Lists) { #Get all list items that have specific term guid. $ListItems = Get-PnPListItem -List $List.Title | Where-Object {$TermGuid -in $_.FieldValues.TaxKeyword.TermGuid}; #Foreach list item. Foreach($ListItem in $ListItems) { #If remove source term is set. If($Replace) { #Add keyword and remove source. [array]$TermGuids = $ListItem.FieldValues.TaxKeyword.TermGuid; [array]$TermGuids += $AddTermGuid; [array]$TermGuids = $TermGuids | Where-Object {$_ -ne $TermGuid} } Else { #Don't remove anyone. [array]$TermGuids = $ListItem.FieldValues.TaxKeyword.TermGuid; [array]$TermGuids += $AddTermGuid; } #Set the keyword on the item. Set-PnPListItem -List $List.Title -Identity $ListItem.Id -Values @{"TaxKeyword"=$TermGuids}; } } } #Add the keyword. Add-SPTaxKeyword -Url "https://contoso.sharepoint.com/sites/intranet" -Credential (Get-Credential) -TermGuid "fd9e6751-e7c2-4a71-80ec-486a65eb1ed2" -AddTermGuid "6564c2fe-b39e-4454-b11c-5507a7568948" -Replace; |
You are able to get the SharePoint taxonomy keyword GUID through the Get-PnPTerm cmdlet, find more information here.