2016-01-10

PowerShell function to Get Term from SharePoint Term Store

Very useful if you're updating taxonomy fields.
Takes 3 inputs; the Site URL, the Taxonomy field object and the Term string.
The function gets a reference to the site's term store and then executes the GetTerm method, (more info here: TermSet.GetTerms) and finally return a Term object.


function GetTerm([string]$siteUrl, [Microsoft.SharePoint.Taxonomy.TaxonomyField]$oField, [string]$termStr) { if(!$oField.IsTermSetValid) { Write-Host "[ERROR] $($oField.Title) IsTermSetValid is FALSE" return $null; } $taxonomySession = Get-SPTaxonomySession -Site $siteUrl; if(($taxonomySession -eq $null) -or ($taxonomySession -eq $null)) { Write-Host "[ERROR] Taxonomy Session is null, Metadata Service App Proxy default storage location for column specific term sets is CHECKED and the user account has access" return $null } $oTermStore = $taxonomySession.DefaultSiteCollectionTermStore; if($oTermStore -eq $null) { $oTermStore = $taxonomySession.TermStores[0]; } if($oTermStore -eq $null) { Write-Host "[ERROR] Unable to get a valid Term Store.`nEnsure $(whoami) is a Term Store administrator.`nEnsure the Managed Metadata Service Proxy property 'This service application is the default storage location for column specific term sets.' is checked." Red exit } $oTermSet = $oTermStore.GetTermSet($oField.TermSetId); [System.Guid]$gTermId = $oField.AnchorId; [int]$LCID = 1033; if(($gTermId.ToString() -eq "00000000-0000-0000-0000-000000000000") -or ($gTermId -eq $null)) { $oTerm = $oTermSet.GetTerms($termStr, $LCID, $true)[0]; if($oTerm -eq $null) { Write-Host "[ERROR] Term value: $termStr not found in TermSet $($oTermSet.Name)" Red } } else { $oAnchorTerm = $oTermSet.GetTerm($gTermId); $oTerm = $oAnchorTerm.Terms[$termStr]; if($oTerm -eq $null) { Write-Host "[ERROR] Term value: $termStr not found in $($oTermSet.Name);$($oAnchorTerm.GetPath())" Red } } return $oTerm }
Below is an example of how to use the function and the returned Term object to set the default value for a field.

$oField = $oWeb.Fields.GetField("Document Type") $oTerm = GetTerm $oWeb.Site.Url $oField "Proposal" if($oTerm -ne $null) { $taxonomyValue = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($oField); $taxonomyValue.TermGuid = $oTerm.Id.ToString(); $taxonomyValue.Label = $oTerm.Name; $oField.DefaultValue = $taxonomyValue.ValidatedString; $oField.PushChangesToLists = $true $oField.Update($true) Write-Host "Setting Default Value $($oField.TypeAsString):$($oField.Title) : '$($taxonomyValue.ValidatedString)'" Yellow }

No comments :

Post a comment