Monday, February 9, 2015

Working with images in Sitecore Powershell

Attaching images to Sitecore items is super easy thanks to the Sitecore API and Sitecore powershell. In this scenario, I've been given a few thousand images I need to attach to Sitecore items. While my initial thought was to invest in Interns to shove the work off to, there is a nicer, easier, more efficient way.

Getting my cue from this blog post on the basics of the Sitecore media API I just needed to translate that to the powershell way of doing it. First off, we're going to need access to the Sitecore API, and that's going to require this line to import in the namespace we'll need (Sitecore.Resources.Media) which is contained in Sitecore.Kernel.dll.
001
Add-Type -Path 'C:\pathtoyours\Sitecore.Kernel.dll'

Now that we've imported the DLL we have access to the full Sitecore Media Library API. This helper function takes care of uploading our image and returning us the GUID we need.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
Function Upload-Image{
  param([io.fileinfo]$sourceFile,$destinationDir)

  $destinationPath = [string]::Format("{0}/{1}",$destinationDir.TrimEnd("/"),$sourceFile.basename)

  $uploader = new-object sitecore.resources.media.mediacreator
  $options = new-object sitecore.resources.media.mediacreatoroptions
  $options.AlternateText = $sourcefile.BaseName
  $options.Destination = $destinationPath
  $result = $uploader.CreateFromFile($sourceFile.FullName,$options)

   Return $result.id.Guid.ToString("B")
  
}


One other thing to keep in mind is special characters you may have to sanitize out of your filenames, you can see a list of currently configured special characters by checking the InvalidItemNameChars property on your Sitecore configuration

001
[Sitecore.Configuration.Settings]::InvalidItemNameChars


Once we have our GUID from our image, there's one last little piece we have to do before setting it and that's formatting the GUID into the correct Sitecore XML like so:
001
002
$imageSitecoreFormat = [string]::Format("<image mediaid=""{0}"" />",$imageGuid)

At this point we just set it on the Sitecore object and we're ready to go!
001
002
003
004
$sitecoreItem = get-item master:\content\somesitecoreitem
$sitecoreItem.beginedit()
$sitecoreItem.ImageField = $imageSitecoreFormat
[void]$sitecoreItem.EndEdit()


No comments:

Post a Comment