Last week I had to delete a bunch of Sitecore media items included on a CSV file. First, I found the function Import-CSV which lets us to read a CSV file as follows.
Import-CSV "[Csv file path]"
Additionally, to delete Sitecore items can be used the function Remove-Item passing as parameter the Sitecore item path as bellow.
Remove-Item -Force -Path [Sitecore item path]
I realized some media items couldn’t be deleted because of some known CMS errors such as “Some of the selected items are in resources and cannot be deleted”. Unfortunately, as the Remove-Item function doesn’t return any result from the operation, I needed to verify if the media item still existed. The function Test-Path is great because returns true in case the Sitecore item exists. Only as a clarification, if the Get-Item is used the produces an error when the Sitecore item doesn’t exist.
$existItem = Test-Path -Path [Sitecore item path]
The items which couldn’t be deleted are displayed in console and also are returned from a custom function named Get-ProcessMediaNotDeleted. The result are formatted and displayed in a grid to the user.
The complete example is shown bellow.
#Read Function to return the media items not deleted
function Get-ProcessMediaNotDeleted {
#Read CSV file from a path
$importList = Import-CSV "C:\files\mediaitems.csv"
foreach ( $row in $importList )
{
#Remove item from the path
Remove-Item -Force -Path $row.Path
#Check if the item was not deleted to include it into the result report
$existItem = Test-Path -Path $row.Path
if ($existItem)
{
$currentItem = Get-Item -Path $row.Path
write-host "Still exist Item path: " $row.Path
$currentItem
}
}
}
# Setup a hashtable to make a more readable script.
$props = @{
InfoTitle = "Media Items not deleted"
InfoDescription = "Lists all media items that are not deleted."
PageSize = 25
}
#Call the main function
Get-ProcessMediaNotDeleted |
Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
@{Label="Updated"; Expression={$_.__Updated} },
@{Label="Updated by"; Expression={$_."__Updated by"} },
@{Label="Created"; Expression={$_.__Created} },
@{Label="Created by"; Expression={$_."__Created by"} },
@{Label="Path"; Expression={$_.ItemPath} }
The CSV file must have a unique column with the Sitecore media item path value named Path.
Hope this script can help you with some similar requests related to Sitecore item operations and PowerShell. See you next time.