Tuesday, 14 August 2012

Bulk Updating a Taxonomy Field Value on List Items with PowerShell

It's pretty easy to update the value of a taxonomy field on a collection of list items using PowerShell. Basically, you get a collection of list items, get a reference to the taxonomy field, and then loop through the items, using the SetFieldValue method of the taxonomy field to update the taxonomy field value of each item. Here's how:

1. Get the taxonomy session for the site collection

$ts = Get-SPTaxonomySession -Site http://myweb

2. Get the term store

$tstore = $ts.TermStores[0]

3. Get the term group that contains the termset for the taxonomy field you're updating.
# To list the term group names: $tstore.Groups | FT -AutoSize Name

$tgroup = $tstore.Groups["MyTermGroupName"]

4. Get the termset for the taxonomy field you're updating.
# To list the termsets: $tgroup.TermSets | FT -AutoSize Name
$tset = $tgroup.TermSets["MyTermSetName"]

5. Get the term you want to use to update the list items using the terms ID (or name).
# To list all the terms in the termset: $tset.Terms | FT -AutoSize Name,ID
# Get the term using the term name: $term = $tset.Terms["MyTermName"]

$term = $tset.Terms[[System.Guid]("f5a95261-b9a2-428b-90ce-8f85111dfd55")]

6. Get the SPWeb and List containing the list you want to update

$w = Get-SPWeb http://myweb/subsite
$l = $w.Lists["My List"]

7. Get the first list item, and use it to get a reference to the taxonomy field
$firstItem = $l.Items[0]
$tf = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$firstItem.Fields["MyTaxonomyColumnName"]

8. Loop through the collection of list items and update the value

foreach($i in $l.Items){if($i.Title -like "*Presentation*"){$tf.SetFieldValue($i, $term);$i.Update();Write-host "Updated"$i.Title;}}

You could (and should) write this a little more efficiently, especially if the list is large, by using a query to get your collection of items to loop through (more efficient than looping through the entire list);

$ic = $l | ?{$_.Title -like "*Presentation*"}
foreach($i in $ic){$tf.SetFieldValue($i, $term);$i.Update();Write-host "Updated"$i.Title;}