June 29, 2012
12 Comments
During, a recent project I had to create Term Stores automatically by using PowerShell. In SharePoint you can save TermStores in .csv files and upload them with the GUI, so If it can be done with the GUI, there’s always a way to do it in PowerShell. After some searches on Google, I found the TechNet article (http://technet.microsoft.com/en-us/library/ee424396.aspx) that explains the format in which the .csv file must be. However a small mistake can mess everything up.
Luckily, I found this great Excel Macro on the Web done by Wictor Wilén.
When you’re done writing all your metadata, just click the “Create Term Store File”. The excel macro does it for you in a .txt. However, I changed the extension to .csv to make sure that it works well with SharePoint.
Now, here is the code to import it into SharePoint.
function ImportTermSet([Microsoft.SharePoint.Taxonomy.TermStore]$store, [string]$groupName, [PSCustomObject]$termSet) {
function ImportTerm([Microsoft.SharePoint.Taxonomy.Group]$group,
[Microsoft.SharePoint.Taxonomy.TermSet]$set,
[Microsoft.SharePoint.Taxonomy.Term]$parent,
[string[]]$path) {
if ($path.Length -eq 0) {
return
} elseif ($group -eq $null) {
$group = $store.Groups | where { $_.Name -eq $path[0] }
if ($group -eq $null) {
$group = $store.CreateGroup($path[0])
}
} elseif ($set -eq $null) {
$set = $group.TermSets | where { $_.Name -eq $path[0] }
if ($set -eq $null) {
Write-Host “Create $path[0]”
$set = $group.CreateTermSet($path[0])
Write-Host “Created $path[0]”
}
} else {
$node = if ($parent -eq $null) { $set } else { $parent }
$parent = $node.Terms | where { $_.Name -eq $path[0] }
if ($parent -eq $null) {
$parent = $node.CreateTerm($path[0], 1033)
}
}
ImportTerm $group $set $parent $path[1..($path.Length)]
}
$termSetName = $termSet[0].”Term Set Name”
$termSet | where { $_.”Level 1 Term” -ne “” } | foreach {
$path = @($groupName, $termSetName) + @(for ($i = 1; $i -le 7; $i++) {
$term = $_.”Level $i Term”
if ($term -eq “”) {
break
} else {
$term
}
}
)
ImportTerm -path $path
}
}
$url = “http://vlad.test.loc”
$session = Get-SPTaxonomySession -Site $url
$store = $session.TermStores[“Managed Metadata Service”]
$termSet = Import-Csv “C:Vladmetameta1.csv”
ImportTermSet $store “vladcatrinescublogtermstore” $termSet
$store.CommitAll()
Start-Sleep -Seconds 10;
Say Thanks if it helped.