Sitecore PowerShell Rendering Helper Functions
For a past project, I had to write a lot of PowerShell for Sitecore migration scripts. One of the tasks that had to be done repeatedly was adding new Renderings to pages and changing Rendering data sources. Necessarily, I wrote a couple of functions to do so.
Adding a new rendering with its data source:
function Add-NewRendering {
param (
$databaseName, # master
$dataSourceID, # Sitecore ID of the Datasource Item
$pageItem, # Sitecore ID of the Page Item where the Rendering will live
$placeHolder, # Placeholder path
$renderingItemID, # Sitecore ID of the Rendering Item under /sitecore/Layouts
$renderingIndex # Index where the rendering will be inserted
)
$renderingItem = Get-Item -Path "$($databaseName):$($renderingItemID)"
if (-Not $renderingItem) {
# Custom method to emit error messages to the console
ErrorMessage -errMsg "Add-NewRendering: Could not fetch rendering item :$($databaseName):$($renderintItemID)"
return
}
$renderingInstance = $renderingItem | New-Rendering -Placeholder $placeHolder
$renderingInstance.Datasource = $dataSourceID
if(-not $renderingIndex)
{
# Add-Rendering and Set-Rendering are the SPE-Provided methods
Add-Rendering -Item $pageItem -Placeholder $placeHolder -Instance $renderingInstance -PassThru |
Set-Rendering -Item $pageItem | Out-Null
}
else
{
# Add-Rendering and Set-Rendering are the SPE-Provided methods
Add-Rendering -Item $pageItem -Placeholder $placeHolder -Instance $renderingInstance -PassThru |
Set-Rendering -Item $pageItem -Index $renderingIndex | Out-Null
}
}
Changing the datasource of an existing rendering:
function Add-NewRenderingDatasource {
param (
$databaseName, # master
$dataSourceID, # Sitecore ID of the Datasource Item
$pageItem, # Sitecore ID of the Page Item where the Rendering lives
$placeHolder, # Placeholder path
$renderingItemID # Sitecore ID of the Rendering Item under /sitecore/Layouts
)
$renderingItem = Get-Item -Path "$($databaseName):$($renderingItemID)"
if (-Not $renderingItem) {
# Custom method to emit error messages to the console
ErrorMessage -errMsg "Add-NewRenderingDatasource: Could not fetch rendering item :$($databaseName):$($renderintItemID)"
return
}
$renderingInstance = Get-Rendering -Item $pageItem -Rendering $renderingItem
if (-not $renderingInstance) {
# Call the Add-NewRendering function, above
$renderingInstance = Add-NewRendering -databaseName $databaseName -dataSourceID $dataSourceID -pageItem $pageItem -placeHolder $placeHolder -renderingItemID $renderingItemID -renderingIndex -1
}
if ($renderingInstance) {
$renderingInstance.Datasource = $dataSourceID
Set-Rendering -Instance $renderingInstance -Item $pageItem
}
else {
ErrorMessage "Add-NewRenderingDatasource: Could not create new renderingInstance for page: $($pageItem.Paths.FullPath)"
}
return $renderingInstance
}