Thursday, January 22, 2015

Set Managed Metadata Field using CSOM via PowerShell in SharePoint online (Office 365)

Context: I was working on a project to migrate data from Lotus notes to SharePoint online. In this context, I had to use Client object model to create list items and set the values of the fields in the list. One of the challenge that I came across was how to set a managed metadata field value using CSOM and PowerShell.

Solution: The following is the code that I wrote to achieve this task. I used an example that was using JSOM to set the Managed metadata field. I converted the same logic using CSOM and PowerShell.
cls

#Your SharwPoint online Credentials
$siteUrl = “https://test.sharepoint.com/sites/dev3”
$username = "testAccount@test.onmicrosoft.com"
[string]$pwd = “Password“
$password = $pwd | ConvertTo-SecureString -AsPlainText -Force
$listName = "Taxonomy List";

# Load the Client object Model Assemblies

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Taxonomy")

function getContext()
{
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
    $context.Credentials = $credentials

    return $context;
}
$context = getContext;

# load the List
$mainList = $context.Web.Lists.GetByTitle($listName);
$context.Load($mainList);
$context.ExecuteQuery();

# load the Taxonomy Field
$TaxonomyKategorieFld = $mainList.Fields.GetByInternalNameOrTitle($taxonomyField) 
$context.Load($TaxonomyKategorieFld)
$context.ExecuteQuery();

# Create the item object in the Taxonomy List
$itemCreationInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation;
$item = $mainList.AddItem($itemCreationInfo);
$item.set_item("Title","Test Taxonomy Item");
$item.Update();

# Create Taxonomy Session
$sTaxonomySession = [Microsoft.SharePoint.Client.Taxonomy.TaxonomySession]::GetTaxonomySession($context);
$sTaxonomySession.UpdateCache();
$context.Load($sTaxonomySession);
$context.ExecuteQuery();

# Load Default Term Store (Site Settings --> Term Store Management) 
$sTermStore = $sTaxonomySession.GetDefaultSiteCollectionTermStore();
$context.Load($sTermStore);
$context.ExecuteQuery();


if($sTermStore.IsOnline)
{
    $sGroup = $sTermStore.Groups.GetByName($sGroupName); # Get the Term Group
    $sTermSet = $sGroup.TermSets.GetByName($tsName); # Get the Term Set
    $context.Load($sTermSet);    
    $context.ExecuteQuery();
    $terms = $sTermSet.GetAllTerms(); # Load all the Terms in the TermSet
    $context.Load($terms);
    $context.ExecuteQuery();
            
    $txField = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo").
               MakeGenericMethod([Microsoft.SharePoint.Client.Taxonomy.TaxonomyField]).
               Invoke($context, $TaxonomyKategorieFld)    
    $termQuery = "Kunden";
    $termQuery1 = "Acme";
    $termValues = @();
    foreach($term in $terms)
    {
        # When Kunden or Aceme Terms found, add to the Taxonomy Field
        if(($term.Name -eq $termQuery) -or ($term.Name -eq $termQuery1)) 
        {
            $termValues +=  "-1;#" + $term.Name + "|" + $term.Id;
            $termValuesString = $termValues -join ";#"
        }    
    }    
        
    $termValues = new-object Microsoft.SharePoint.Client.Taxonomy.TaxonomyFieldValueCollection($context, $termValuesString, $txField)
    $txField.SetFieldValueByValueCollection($item, $termValues);
    $item.Update();
    $context.Load($item);
    $context.ExecuteQuery();
}

$context = $null;
Reference: http://sharepoint.stackexchange.com/questions/113146/how-do-you-properly-write-to-a-managed-metadata-column-from-jsom-sharepoint-20

Cheers.. :)

4 comments:

  1. Thank you!!!!!!!! Works perfect :-)

    ReplyDelete
  2. I am getting the below exception:"exception calling executequery with 0 arguments:"Specified method is not supported

    ReplyDelete
  3. You might be doing something wrong. Send me the code that I are writing and I will look into it.. :)

    ReplyDelete