Skip to content

Instantly share code, notes, and snippets.

@pveller pveller/import.ps1
Last active May 17, 2019

Embed
What would you like to do?
Sitecore Content Import with Powershell
# http://jockstothecore.com/content-import-with-powershell-treasure-hunt
function NormalizeName($name)
{
# replace all special symbols with single spaces
$name = $name -replace "[^a-zA-Z0-9]", " " -replace "\s+", ""
return $name.Trim()
}
$media = Get-Item "/sitecore/media library"
$folder = Get-Item "/sitecore/content"
$template = Get-Item "/sitecore/templates"
# Note: shorten for the blog post. you would want tooltips
$dialog = Read-Variable -Parameters `
@{ Name = "media"; Title = "Source"; Root="/sitecore/media library/"; Editor="item"}, `
@{ Name = "folder"; Title = "Destination"; Root="/sitecore/"; Editor="item"}, `
@{ Name = "template"; Title = "Type"; Root="/sitecore/templates/"; Editor="item"} `
-Description "This script will convert CSV data into content items." `
-Width 800 -Height 600 `
-Title "Simple CSV Import Utility" `
-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
{
foreach ($record in $csv)
{
$name = NormalizeName $record.Name
Write-Host "Normalized [$($record.Name)] => [$name]"
$item = New-Item -Path $folder.Paths.FullPath -Name $name -ItemType $template.Paths.FullPath
$item.Editing.BeginEdit()
$item["__Display name"] = $record.Name
$record | `
Get-Member -MemberType Properties | `
ForEach-Object { $item["$($_.Name)"] = $record."$($_.Name)" }
$item.Editing.EndEdit()
Write-Host "Created $($item.Paths.FullPath) for $($record.Name)"
}
}
finally
{
$bulk.Dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.