1

I have a Treelist field type on an item which I am trying to update using a Powershell script which is reading data from a CSV file. I am using the following snippet in my script:

#Create an array of values from CSV (comma separated list)
$services = $row."Services".Split(",") 

foreach($service in $services) {
   $item["Service"] += $service
   $item["Service"] += "|" 
}           

But I get the following result:

enter image description here

Does anyone know the correct way to update this type of field?

2 Answers 2

0

The issue is that you are reading the values from your CSV and directly binding into the TreeList field but the items you are binding don't exist in Sitecore.

If you will see the raw value of the TreeList Field it's a combination of Sitecore Item IDs with a pipe(|) separator. So in your case, those items do not exist in the Sitecore database and that's why they are showing like this.

So the code will be something like this.

$services = $row."Services".Split(",");
if($itemsGuidFromYourTreeListField -ne $null)
{
    foreach($service in $services)
    {
       # Get item by it's Path 
       $currentItem = Get-Item -Path $service.ItemPath
       
       if($currentItem){
       { 
           # Write logic to append the ID of $currentItem in pipe separated ID's
       }
    }
}

$item = Get-Item -Path "master:" -ID "<Your Item ID>"

$item.Editing.BeginEdit();
$item.Fields["YourTreeListField"].Value = "<pipe separated ID field>";
$item.EndEdit();

And if you have the ID's of items that exist in your Sitecore database from your CSV then you don't need to use the method Get-Item to find those. In this case, you can loop through to create a string like this.

{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}|{652F3B26-3474-4C79-8A86-AC70CBC26F91}|{D119BAAE-A1D3-46B0-AE2D-748D50B3C94D}

And directly use begin and end edit to update your field.

Hope this helps.

0

You are in the right direction just a few tweaks are required to make it work. I tried with the below script and it worked for me. also, ensure your CSV file have valid IDs for items that you want to set as selected in your tree list field.

This script will add item ids into treelist if it is null and if there are already selected items then it appends new ids that read from CSV.

$item = get-item 'master:/sitecore/content/Home';

$services = '{4167291E-80EC-47D1-850E-B01B9322575E},{298C3E39-3F45-4864-9A3D-E5E7C2816738},{8B9A079B-E5FD-4B9E-962B-5B5E94E85EAC}'

foreach($service in $services.Split(",")) {

    $item.Editing.BeginEdit()
    
    if (![string]::IsNullOrEmpty($item["Service"]))
    {
      $item["Service"] += "|";
    }

    $item["Service"] += $service

    $item.Editing.EndEdit()
}

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.