Saturday 5 April 2014

Add Terms in Term Set in Sharepoint 2013 Managed Metadata Service Application using Powershell

Below code for add terms in term set in SharePoint 2013 using Power Shell Script.


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["Test - Managed Metadata Service Application"] 
$folder= Get-ChildItem -Path C:\Termset\ -Recurse -Include *.csv
$folder | ForEach-Object {
$FileName ="C:\Termset\"+$_.Name
$termSet = Import-Csv $FileName
ImportTermSet $store "Test Term Sets" $termSet
}
$store.CommitAll() 



No comments:

Post a Comment