Create a Term Group at the Site Collection Level

By default, when you create Groups in the Managed Metadata Service Application, they become available across the board. SharePoint however also has the concept of Site Collection groups, that are only available inside a given site collection, and not made available outside that boundary. These special groups are automatically created when you activate the managed navigation at the site collection level:
Managed Metadata Navigation Group

Doing this automatically creates a new Site Collection group named “Site Collection – <URL with dashes>”. We know that this group is local to the site collection due to the fact that it is listed under the blues dashed line, as shown in the screenshot below:
Local Site Collection Taxonomy Group

In some cases however, we want to automate the creation of that local Site Collection Group, instead of having to manually do it via the interface. In order to achieve this, I have created the following PowerShell script, that allows us to create that Term Group using Reflection. In the script below, I am creating the local Term Group on a site collection located at http://intranet.contoso.com/sites/HR, and the name of my default Managed Metadata Service Application for storing terms is named MMS.

function New-SiteCollectionGroup
{
    [CmdletBinding()]
    [OutputType([System.GUID])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $SiteCollectionUrl,

        [Parameter(Mandatory = $true)]
        [System.String]
        $ServiceApplicationName
    )

    $taxonomySite = Get-SPSite $SiteCollectionUrl
    $taxonomySession = Get-SPTaxonomySession -site $taxonomySite
    $termStore = $taxonomySession.TermStores[$ServiceApplicationName]    

    $BINDING_FLAGS = ([System.Reflection.BindingFlags]::DeclaredOnly -bOr [System.Reflection.BindingFlags]::NonPublic -bOr [System.Reflection.BindingFlags]::Instance)
    $Taxonomy = $termStore.GetType()
    $groupName = "Site Collection - " + $SiteCollectionUrl.Replace("http://", "").Replace("/", "-")
    $methodParameterTypes = [type[]]@($groupName.GetType(), $taxonomySite.GetType());
    $METHOD_CREATESITECOLLECTIONGROUP = $Taxonomy.GetMethod("CreateSiteCollectionGroup", $BINDING_FLAGS, $null, $methodParameterTypes, $null)
    $parameters = [object[]]@($groupName, [Microsoft.SharePoint.SPSite]$taxonomySite);
    $newGroup = [Microsoft.SharePoint.Taxonomy.Group]$METHOD_CREATESITECOLLECTIONGROUP.Invoke($termStore, $parameters)
    return $newGroup.Id
}

New-SiteCollectionGroup -SiteCollectionUrl http://intranet.contoso.com/sites/HR -ServiceApplicationName MMS

Leave a Reply

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