Tags

,

Hi Friends,

Recently, I have been working on different PowerShell scripts to help out to create reports.

I am sharing one more PowerShell script to read the MultiListField. You can use the “Value” as a standard method to read the MultiList Values. But that will give you the IDs as a string. You have to use the string operations to split and then loop through.

The property TargetIDs returns the Array of IDs. Using the IDs, you can get the item. The multiListField has one more method – GetItems(). This method returns an array of Items. But when I used that, it didn’t return the templated field. It returned only the default standard fields.

Purpose of the Script

The Item consists of a MultiList. We have a list of Persons stored in the MultiList and I want to find the name, ID, whether the person is active or not, etc.

  • Reads the MultiList
  • Loop through the IDs
  • Get the Item for each ID
  • Populate the Custom Object
  • Populate a field value based on a condition

The script reads through an Item

    $multiListField = [Sitecore.Data.Fields.MultilistField]$pageItem.Fields["PersonList"]
    $personItems = $multiListField.TargetIDs

Another important part of the below script is to populate custom objects with a value based on a condition.

            "Active" = if ($item."Active" -eq "1") {"Active"} else {'Inactive'}

The Full script as below

function  FindmultiListField
{
    $itemPath = "/sitecore/content/ITEMPATH"   
    $pageItem= Get-Item -Path "master:/$itemPath" 
    
	
    $multiListField = [Sitecore.Data.Fields.MultilistField]$pageItem.Fields["PersonList"]
    
    $personItems = $multiListField.TargetIDs
    
    foreach($person in $personItems){
        $item = Get-Item -Path "master:/$person" 
        $customItem = [pscustomobject]@{
            "ID"=$item.ID
            "DisplayName"=$item.DisplayName
            "Active" = if ($item."Active" -eq "1") {"Active"} else {'Inactive'}
            "Version"=$item.Version
            "Last Updated"=$item.__Updated 
            "EMPL ID"=$item."EmployeeID"
        }
        
<# 
#Second option to conditional value 
if ($item."Active" -eq "1") {
            $customItem | Add-Member -Type NoteProperty -Name 'Active' -Value "Active"
        }
        else{
            write-host $item.DisplayName  $item."Active"
            $customItem | Add-Member -Type NoteProperty -Name 'Active' -Value "Inactive"
        }#>
        $customItem    
    }
}

$items = FindmultiListField
$items | Show-ListView 
Close-Window