SharePoint Term Store with PowerShell and JavaScript


The SharePoint Term Store is a robust taxonomy management tool that enables organizations to standardize metadata across sites, lists, and libraries. It provides a centralized way to define, maintain, and deploy terms used to classify content, improving searchability and organization.


What is the Term Store?

The Term Store is part of SharePoint’s Managed Metadata Service. It allows administrators to define:

  • Term Groups: A container for term sets, typically scoped to departments or large organizational divisions.
  • Term Sets: Collections of related terms.
  • Terms: Individual items in a term set used to tag content.

Key Benefits of Using Term Store

  • Standardization: Ensures consistent use of terms across the organization.
  • Hierarchical Organization: Supports nested terms for detailed categorization.
  • Improved Search: Tagged content is easier to locate using metadata-based queries.
  • Flexibility: Supports multilingual labels and synonyms.

Creating and Updating SharePoint List Items with Term Store Metadata

When working with SharePoint lists integrated with the Term Store, terms are used to populate metadata columns. Here’s how you can create and update list items programmatically.

Setup: Add a Managed Metadata Column
  1. Navigate to your list or library.
  2. Go to Settings > List Settings.
  3. Add a column with type Managed Metadata.
  4. Link it to a term set in the Term Store.

Creating a List Item with Term Store Metadata

Below is a PowerShell example for creating a list item and setting a Term Store metadata value

# Connect to SharePoint
Connect-PnPOnline -Url "https://yourtenant.sharepoint.com/sites/YourSite" -UseWebLogin

# Specify term details
$termStoreName = "Managed Metadata Service"
$termGroupName = "Department"
$termSetName = "Locations"
$termName = "Canada"

# Get term details
$term = Get-PnPTerm -TermSet $termSetName -TermStore $termStoreName -Group $termGroupName | Where-Object { $_.Name -eq $termName }

# Create a list item
$listTitle = "Your List Name"
$item = Add-PnPListItem -List $listTitle -Values @{
    Title = "New Item"
    "ManagedMetadataColumnName" = $term.Id
}

Write-Host "Item created successfully."
Updating a List Item

Updating a list item with Term Store metadata is straightforward. Here’s how:

# Update an existing item
$itemId = 1 # Replace with the actual item ID
Set-PnPListItem -List $listTitle -Identity $itemId -Values @{
    "ManagedMetadataColumnName" = $term.Id
}

Write-Host "Item updated successfully."

Basic Concepts to Know About the Term Store
  1. Term IDs: Each term has a unique GUID, which is used in scripts.
  2. Term Navigation: Terms can be hierarchical, allowing you to build parent-child relationships.
  3. Synonyms and Labels: Terms support alternate names and language-specific labels.
  4. Permissions: Users need appropriate permissions to use and edit terms.
  5. Versioning and Deprecation: Terms can be versioned or deprecated to manage taxonomy changes effectively.

Best Practices for Managing the Term Store
  1. Plan Before Implementation: Define your taxonomy with input from key stakeholders.
  2. Use Descriptive Names: Make term names intuitive for users.
  3. Enable Feedback Loops: Allow users to suggest new terms or updates.
  4. Audit Regularly: Review and update term sets periodically to maintain relevance.

Creating and Updating SharePoint List Items with Term Store Metadata

In addition to PowerShell, SharePoint supports integration with the Term Store using JavaScript and REST APIs. Let’s explore how to achieve this functionality programmatically.

Using JavaScript with REST API
Prerequisites
  1. Add a Managed Metadata column to your list in SharePoint.
  2. Obtain the term set ID or term ID from the Term Store.
1. Creating a List Item with Term Store Metadata

Below is an example using JavaScript to add a list item with a Managed Metadata column.

function createListItem() {
    const listName = "YourListName"; // Replace with your list name
    const termLabel = "Canada"; // Term Label
    const termId = "c2d7e5ad-4bf3-4825-a49d-abcde1234567"; // Replace with your term ID (GUID)
    const itemTitle = "New List Item"; // Item Title

    const metadataField = {
        "__metadata": { type: "SP.Taxonomy.TaxonomyFieldValue" },
        Label: termLabel,
        TermGuid: termId,
        WssId: -1
    };

    const itemProperties = {
        __metadata: { type: "SP.Data.YourListNameListItem" },
        Title: itemTitle,
        ManagedMetadataColumn: metadataField
    };

    $.ajax({
        url: `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('${listName}')/items`,
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(itemProperties),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            console.log("Item created successfully:", data.d);
        },
        error: function (error) {
            console.error("Error creating item:", error);
        }
    });
}
2. Updating a List Item

Use the following JavaScript function to update a list item with Managed Metadata.

function updateListItem(itemId) {
    const listName = "YourListName"; // Replace with your list name
    const termLabel = "USA"; // New Term Label
    const termId = "a123e5ad-7bf3-4825-b49d-xyz123456789"; // Replace with new term ID

    const metadataField = {
        "__metadata": { type: "SP.Taxonomy.TaxonomyFieldValue" },
        Label: termLabel,
        TermGuid: termId,
        WssId: -1
    };

    const itemProperties = {
        __metadata: { type: "SP.Data.YourListNameListItem" },
        ManagedMetadataColumn: metadataField
    };

    $.ajax({
        url: `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('${listName}')/items(${itemId})`,
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(itemProperties),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "MERGE",
            "If-Match": "*"
        },
        success: function () {
            console.log("Item updated successfully");
        },
        error: function (error) {
            console.error("Error updating item:", error);
        }
    });
}
Key REST Endpoints for Term Store
  • Get Term Sets
GET /_api/v1/termstore/groups/{groupId}/sets
  • Get Terms in a Term Set
GET /_api/v1/termstore/groups/{groupId}/sets/{setId}/terms
  • Create a Term
POST /_api/v1/termstore/groups/{groupId}/sets/{setId}/terms
{
    "name": "New Term Name",
    "parent": { "id": "ParentTermId" }
}

Basic Concepts to Know About the Term Store
  1. Term Labels: Each term can have multiple labels for multilingual support.
  2. Term GUID: A unique identifier for terms, essential for REST API operations.
  3. WssId: Used internally by SharePoint but generally set to -1 when assigning terms programmatically.
  4. Permissions: Ensure the user running the script has adequate permissions to the Term Store.

The SharePoint Term Store is an indispensable tool for metadata management in SharePoint. Whether you’re managing content manually, using PowerShell, or leveraging REST APIs and JavaScript, a clear understanding of the Term Store can help you build scalable, efficient solutions.

Integrating the Term Store with SharePoint lists and libraries not only improves content organization but also ensures consistent metadata usage across your organization. Armed with these examples, you’re ready to start leveraging the Term Store in your SharePoint solutions!


Automation Branding Cascading StyleSheet Cheat Sheet Collaboration Competitors Content Type CSS Date Formats Dates Design Flows HTML5 Intl Issues Javascript JSON Format View Limitation Limitations Luxon Microsoft Teams ModernScriptEditor NodeJs O365 Office 365 OneDrive Overflow PnP Power Automate PowerShell Rest Endpoint ScriptEditor Send an HTTP Request to SharePoint SharePoint SharePoint Architecture SharePoint Designs SharePoint Modern SharePoint Online SPFX SPO Styling Sync Teams Teams App Workflows

Leave a Comment

Your email address will not be published. Required fields are marked *