Monday, 6 April 2015

SharePoint : Update Managed Metadata Column Using PowerShell

Greetings Readers!
In this blog we will discuss how to update the managed metadata column of a SharePoint site. Those who have worked on it can understand how frustrating it is to try to update it without knowing the proper way. I remember the first time when I had tried to write a PowerShell script to update values of a taxonomy field of document library. I was stuck like anything. But I assure you once you know the correct way to reference a SharePoint Managed Metadata field it becomes very easy.

Here is a sample script showing how to do it.

$siteobj = new-object Microsoft.SharePoint.SPSite("http://your-site-url")
$web = Get-SPWeb "http://your-site-url"
#creating the taxonomy session object
$session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($siteobj)
if($session -eq $null)
        Write-Host "Failed to create taxonomy session"
#Getting the term (new value) to which we want to update the column
$termstore = $session.TermStores["termstore name"]
$group = $termstore.Groups["group name"]
$termset = $group.TermSets["termset name"]
$term = $termset.Terms["term name"]
#List/Library we want to update
$list = $web.Lists["your list name"]
$taxfield =  $list.Fields["your column"] -as [Microsoft.SharePoint.Taxonomy.TaxonomyField]
foreach($item in $list.Items)
      #SetFieldValue function is used to update taxonomy field
      write-host $_.exception

        if($web -ne $null)
              write-host -ForegroundColor Green "Disposing the web Object.."


You can make an input xml file from where you can read the values and do it for multiple site collections in one run. Now you can see how simple it is to update the taxonomy fields. In the end we have used SystemUpdate() function to preserve the metadata of the item like modified, modified by etc. If you don't want then you can use Update or UpdateVersionOverwrite. If you are not sure which one to use visit my previous blog where I have explained their differences. If you have any queries you can leave comments or mail me. Now it's time for a SharePoint fact.

FACT : We all know SharePoint web parts. We can add a web part to a page in a web part zone or outside it. So you will ask what's the difference? The difference is that if you add a web part in web part zone, the properties of that web part are stored in content database and users can view and edit it through browser. But if web parts are added outside the web part zone then it is stored in the aspx page and users can't edit it through browser. They can only see it. So add wisely!

No comments:

Post a Comment

Feel free to share your thoughts...