This blog post explains how to implement a custom command in Sitecore context menu to export Sitecore item data using powerShell. As a prerequisite PowerShell module for Sitecore must be installed on the Sitecore instance. To implement this we need to create a custom command in context menu and associate it with a PowerShell script which would be executed on the click event of context menu item.
The Powershell module provides some sample scripts which can be located in the powershell script library (/sitecore/system/Modules/PowerShell/Script Library)
- Create a Powershell Module using the PowerShell Script Module template
- Create a powershell script under the powershell script module created
- Edit the script item in Powershell ISE to contain the script logic
#gets the current context item $item = Get-Item . $displayname = $item.DisplayName $fields = Get-ItemField $item [string]$display = @("Language","Version","DisplayName") [string]$owner = @("__Owner","__created","Workflow") $display = $display + $fields +$owner $PSExport = Get-Item . -Language * -Version * | select-object $display Import-Function -Name ConvertTo-Xlsx $datetime = Get-Date -format "yyyy-MM-d_hhmmss" $format = & ([scriptblock]::Create($PSExport)) [byte]$outobject = [psCustomObject]$PSExport | Select-Object -Property $format | ConvertTo-Xlsx Out-Download -Name "report-$displayname-$datetime.xlsx" -InputObject $outobject
The above script gets the current context sitecore item and exports the item fields in every language and every version with the fields of the template, include a few standard fields for the report to contain the desired data like the name of the item, Language and Version. The raw values of the respective fields are exported and downloaded in the excel format.
Custom Command In Context Menu
Associate the powershell script with a menu item in the context menu so that user can run reports on the items required.
- Switch to core database
- Create a Menu Item using the Menu Item template. In the following location (/sitecore/content/Applications/Content Editor/Context Menues/Default)
- Populate the display name and message fields.
Message field contains the id of the script which need to be executed on click of the command and the database in which the script resides.
Rebuild the indexes from the developer tab to see the menu item available. You can run the script by clicking on the command in the context menu, which downloads a excel with the desired fields.
Another alternate approach could have been using the list view but it provides options exporting the data to JSON, XML, CSV, Excel, Html. The file downloaded using the list view contains only the date-stamp. Since we would be exporting the data of a single item the default Excel export functionality provided by PowerShell has been incorporated to customize the name of file to be exported to contain the date stamp as well as the item name.