Recursive walk of Tridion tree - TridionPractice/tridion-practice GitHub Wiki

One of the things you will often want to do, for example when creating reports, is to extract from Tridion the contents of an entire sub-tree from the standard hierarchy of publications, folders, structure groups and categories. This recipe shows how you can do this using the Core service via the Powershell.

The basic technique makes use of a function that takes care of the recursion itself. This function: Get-TridionTreeItems is defined in a script in the code repository. (Note: for 2011, you need [this version] (https://github.com/TridionPractice/tridion-practice/blob/2011/TridionPowershellScripts/Get-TridionTreeItems.ps1).

If you examine the function, you will see that the $parent parameter is an IdentifiableObjectData that will act as the root for your search. (Unfortunately, this is the most specific type that includes both publications and other organizational items, so please don't be silly and pass in random things like schemas.) If you pass in null, it will start at the top and enumerate your entire system. (If you're using an industrial scale system, please consider carefully if this is what you want.)

The script loops through the various containers, writes the items to the output, and where appropriate, continues the recursion. Writing the items to the output makes them available in the powershell pipeline, so you end up with a list of all the items, in tree order. We also keep track of the level of recursion, and add this to each item as a custom note property. This means that if you want to display the tree structure later, you can. For example, I was able to use the following snippet to output the titles of all the items in my layout publication indented with tabs to show the hierarchy:


import-module Tridion-CoreService
$core = Get-TridionCoreServiceClient
$layoutpub = $core.Read("tcm:0-4-1",$null)
$layoutpubitems = Get-TridionTreeItems $core $layoutpub
$layoutpubitems | % {"`t"*$_.level + $_.title}

To be honest, this is a trivial application, but there are many occasions when you can do very useful things starting with a list of the tree in your pipeline.