Search code examples
powershellsitecoresitecore8

Sitecore Powershell Reports/ListView: retrieving items from ID returned by the query


A template named "User" has a field called "Location" which is the ID of another item; in Powershell I use Show-ListView to return a list of fields, but Location shows the raw ID, while I would much rather display the Name of the Location involved.

I attempted to retrieve this information, but I'm not sure about which syntax is available within the Powershell query. My attempt is as follows:

Get-Item master: -Query "/sitecore/content/sites/data/people//*[@@templatename='Person']" |
    Show-ListView -property "First Name",
    @{Label="Surname"; Expression={$_."Surname"}},
    @{Label="Location"; Expression={[Sitecore.Context.Database.GetItem]::FromId($_."Location").Title}}

...which yields nothing.

$_."Location"

is the ID of an item; is there a way to retrieve its fields?


Solution

  • The secret lies in the fact that by default Sitecore do not have the convenient properties that are transformed from fields. In this case we're talking about the Title property on your location item. What you can do is:

    1) Fetch the location Item through the provider like so:

    Get-Item master: -Query "/sitecore/content/sites/data/people//*[@@templatename='Person']" |
        Show-ListView -property "First Name",
        @{Label="Surname"; Expression={$_."Surname"}},
        @{Label="Location"; Expression={(Get-Item master:\ -ID $_."Location").Title}}
    

    notice the call to Get-Item in the last line.

    2) if you need to fetch it through the Sitecore API for some reason, you can pipe it to Initialize-Item and we'll wrap those properties around the Item object for you like so:

    Get-Item master: -Query "/sitecore/content/sites/data/people//*[@@templatename='Person']" |
        Show-ListView -property "First Name",
        @{Label="Surname"; Expression={$_."Surname"}},
        @{Label="Location"; Expression={([Sitecore.Configuration.Factory]::GetDatabase("master").GetItem($_."Location") | Initialize-Item).Title}}