Skip to content

Instantly share code, notes, and snippets.

@martinrayenglish
Created December 11, 2016 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinrayenglish/26f835b954ab125e119e98dad4835fc6 to your computer and use it in GitHub Desktop.
Save martinrayenglish/26f835b954ab125e119e98dad4835fc6 to your computer and use it in GitHub Desktop.
Powershell script that targets a CSV file in the media library and creates simple redirect items for each data record
<#
.SYNOPSIS
Script targets a CSV file in the media library and creates simple redirect items for each data record
.NOTES
Martin English
#>
#Target csv file in media library
$media = "/sitecore/media library/import-data"
#Target import location
$folder = "/sitecore/content/MySite/Globals/Url Rewrites/MySite Rewrites/Page Redirects/Imported"
#Template used to create item
$template = Get-Item "/sitecore/system/Modules/Url Rewrite/Templates/Inbound/Simple Redirect"
#Test mode => will create only 4 items if set to true
$test = $false
function NormalizeName($name) {
# replace all special symbols with single spaces
$name = $name -replace "[^a-zA-Z0-9 ]", "" -replace "\s+", " "
return $name.Trim()
}
function CreateRedirect($redirectItem, $csvRecord){
$redirectItem.Editing.BeginEdit()
$redirectItem["Path"] = $csvRecord.Old
[Sitecore.Data.Fields.LinkField]$field = $redirectItem.Fields["Target"]
$field.LinkType = "external"
$field.Url = $csvRecord.New
$redirectItem.Editing.EndEdit()
}
$dialog = Read-Variable -Parameters `
@{ Name = "media"; Title = "Source"; Root=$media; Editor="item"}, `
@{ Name = "folder"; Title = "Destination"; Root=$folder; Editor="item"}, `
@{ Name = "template"; Title = "Type"; Root=$template; Editor="item"} `
-Description "This script will convert CSV data into content items." `
-Width 800 -Height 600 `
-Title "Import" `
-OkButtonName "Import" `
-CancelButtonName "Cancel"
if ($dialog -ne "ok") {
Exit
}
# Read media stream into a byte array
[system.io.stream]$body = $media.Fields["blob"].GetBlobStream()
try {
$contents = New-Object byte[] $body.Length
$body.Read($contents, 0, $body.Length) | Out-Null
}
finally {
$body.Close()
}
# Convert the stream into a collection of objects
$csv = [System.Text.Encoding]::Default.GetString($contents) | ConvertFrom-Csv
$bulk = New-Object "Sitecore.Data.BulkUpdateContext"
try {
$counter = 0
foreach ($record in $csv) {
$name = NormalizeName $record.Name
Write-Host "Old Path: $($record.Old)"
Write-Host "Normalized Name: $($name)"
$redirectItem = New-Item -Path $folder.Paths.FullPath -Name $name -ItemType $template.Paths.FullPath
CreateRedirect $redirectItem $record
#Exit if we are testing
if ($test -and $counter -eq 3) {
break
}
Write-Host "Created $($redirectItem.Paths.FullPath) for $($record.name)"
$counter++
}
}
finally {
$bulk.Dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment