Export SharePoint Terms Group to XML

Here is a PowerShell script to export SharePoint Term Groups to XML

 

param(
	[string]$siteUrl = "http://sharepoint.local:2013",
	[string]$termGroup = "Sample Term Group",
	[string]$exportPath = $null
)


function Add-Snapin {
	if ((Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null) {
		$global:SPSnapinAdded = $true
		Write-Host "Adding SharePoint module to PowerShell" -NoNewline
		Add-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction Stop
		Write-Host " - Done."
	}

	Write-Host "Adding Microsoft.SharePoint assembly" -NoNewline
	Add-Type -AssemblyName "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
	# Disable the above line and enable the line below for SharePoint 2013
	# Add-Type -AssemblyName "Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
	Write-Host " - Done."
}

function Remove-Snapin {
	if ($global:SPSnapinAdded -eq $true) {
		Write-Host "Removing SharePoint module from PowerShell" -NoNewline
		Remove-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue
		Write-Host " - Done."
	}
}

function Get-ScriptDirectory
{
	$Invocation = (Get-Variable MyInvocation -Scope 1).Value
	return Split-Path $Invocation.MyCommand.Path
}

function Export-SPTerms {
    param (
        [string]$siteUrl = $(Read-Host -prompt "Please provide the site collection URL"),
        [string]$termGroupName = $(Read-Host -prompt "Please provide the term group name to export"),
        [string]$saveLocation = $(Read-Host -prompt "Please provide the path of the folder to save the CSV file to")
    )

	if ([IO.Directory]::Exists($saveLocation) -eq $false)
	{
		New-Item ($saveLocation) -Type Directory | Out-Null
	}

	Write-Host "Getting Taxonomy Session";
	$taxonomySession = Get-SPTaxonomySession -site $siteUrl
	$taxonomyTermStore =  $taxonomySession.TermStores | Select Name
	$termStore = $taxonomySession.TermStores[$taxonomyTermStore.Name]
	$fileRootNoteCreated = $false;

	# Ampersands are stored as full width ampersands (see http://www.fileformat.info/info/unicode/char/ff06/index.htm)
	[Byte[]] $amp = 0xEF,0xBC,0x86

	Write-Host "Looping through Term store Groups to find: '$termGroupName'"
	foreach ($group in $termStore.Groups) {
		Write-Host "Checking: '$($group.Name)'"
		$groupName = $group.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&");
		if ($groupName -eq $termGroupName) {

			Write-Host "Looping through Term sets"
		    foreach ($termSet in $group.TermSets) {
            	# Remove unsafe file system characters from file name
				$parsedFilename =  [regex]::replace($termSet.Name, "[^a-zA-Z0-9\-]", "_")

				$file = New-Object System.IO.StreamWriter($saveLocation + "termset_" + $parsedFilename + ".xml")

		        # Write out the headers
		        #$file.Writeline("Term Set Name,Term Set Description,LCID,Available for Tagging,Term Description,Level 1 Term, Level 2 Term,Level 3 Term,Level 4 Term,Level 5 Term,Level 6 Term,Level 7 Term")
				$file.Writeline("<termStore Name='" + $termStore.Name + "' GUID='" + $termStore.ID + "' Group='" + $groupName + "'>");
		        $file.Writeline("`t<termSet Name='" + $termSet.Name + "' GUID='" + $termSet.ID + "' Description='" + $termSet.Description + "'>");
				try {
					Export-SPTermSet $termSet.Terms
				}
				finally {
					$file.Writeline("`t</termSet>");
					$file.Writeline("</termStore>");
			        $file.Flush()
			        $file.Close()
				}
			}
		}
	}
}

function Export-SPTermSet {
    param (
        [Microsoft.SharePoint.Taxonomy.TermCollection]$terms,
		[int]$level = 1,
		[string]$previousTerms = ""
    )

	$tabCount = $level+1;
	if ($level -gt 1) {$tabCount = $tabCount + ($level-1);}

	if ($terms.Count -gt 0)
	{
		$file.Writeline("`t" * $tabCount + "<terms>");
	}

	if ($level -ge 1 -or $level -le 7)
	{
		if ($terms.Count -gt 0 ) {
			$termSetName = ""
			if ($level -eq 1) {
				$termSetName =  """" + $terms[0].TermSet.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&") + """"
			}
			$terms | ForEach-Object {
				$termName = $_.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&");
				$currentTerms = $previousTerms + ",""" + $termName + """";

				$file.Writeline("`t" * $tabCount + "`t<term Name='" + $termName + "' isAvailableForTagging='" + $_.IsAvailableForTagging + "'>");
				$file.Writeline("`t" * $tabCount + "`t`t<description>" + $_.GetDescription() + "</description>");

				if ($level -lt 7) {
					Export-SPTermSet $_.Terms ($level + 1) ($previousTerms + $currentTerms)
				}
				$file.Writeline("`t" * $tabCount + "`t</term>");
			}
		}
	}

	if ($terms.Count -gt 0)
	{
		$file.Writeline("`t" * $tabCount + "</terms>");
	}
}

try {
	Write-Host "Starting export of Metadata Termsets" -ForegroundColor Green
	$ErrorActionPreference = "Stop"
	Add-Snapin

	if (!($exportPath)) {
		$exportPath = (Get-ScriptDirectory)
	}

	Write-Host "Site: $siteUrl" -ForegroundColor Yellow
	Write-Host "Term Group: $termGroup" -ForegroundColor Yellow
	Write-Host "Export Path: $exportPath" -ForegroundColor Yellow

	Export-SPTerms $siteUrl $termGroup $exportPath
}
catch {
	Write-Host ""
    Write-Host "Error : " $Error[0] -ForegroundColor Red
	throw
}
finally {
	Remove-Snapin
}
Write-Host Finished -ForegroundColor Blue

export-terms-xml.ps1 (5.31 kb)