DEV Community

Daniel Gomez
Daniel Gomez

Posted on

1 1 1 1

Backup Sitecore Media Library items with a PowerShell script

Hi! In this blog, we'll find a Sitecore PowerShell script to be able to backup Media Library items in a zip file on the server.



$dataFolder = "C:\inetpub\wwwroot\<YOUR_SITE>\Data"
$mediaLibraryRootPath = "master:/sitecore/media library"

$location = $mediaLibraryRootPath
$dateTime = Get-Date -format "yyyy-MM-d_hhmmss"
$zipName = "Backup Media Library Example"
$zipPath = "$dataFolder/$zipName-$datetime.zip"

function BackupMediaItems {

    [System.Reflection.Assembly]::Load("WindowsBase,Version=3.0.0.0, `
      Culture=neutral, PublicKeyToken=31bf3856ad364e35") | Out-Null

    $ZipPackage=[System.IO.Packaging.ZipPackage]::Open($zipPath, `
      [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite)

    $items = gci -recurse $sourceDir
    [byte[]]$buff = new-object byte[] 40960

    $items = Get-ChildItem -Path $location -Recurse | 
        Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }

    $i = 0
    foreach($item in $items) {
            $i = $i + 1
            if([Sitecore.Resources.Media.MediaManager]::HasMediaContent($item))
            {
              Write-Output "$($i). $($item.ItemPath)"

              $mediaItem = New-Object "Sitecore.Data.Items.MediaItem" $item;
              $mediaStream = $mediaItem.GetMediaStream();
              $fileName = Resolve-Path -Path $item.ProviderPath -Relative
              $nm = $item.Name + "." + $item.Extension

              $fileName = "$fileName.$($item.Extension)" `
                -replace "\\","/" -replace "./", "/"
              # Print out the file - the list will show up once the file is downloaded
              "Added: $fileName"

              # Show progress for the operation
              Write-Progress -Activity "Zipping Files " `
                -CurrentOperation "Adding $fileName" `
                -Status "$i out of $($items.Length)" `
                -PercentComplete ($i *100 / $items.Length)

              $partUri = New-Object System.Uri($fileName, [System.UriKind]::Relative)
              $partUri = [System.IO.Packaging.PackUriHelper]::CreatePartUri($partUri);
              $part = $ZipPackage.CreatePart($partUri, `
                "application/zip",  `
                [System.IO.Packaging.CompressionOption]::Maximum)
              $stream=$part.GetStream();

              do {
                $count = $mediaStream.Read($buff, 0, $buff.Length)
                $stream.Write($buff, 0, $count)

              } while ($count -gt 0)

              #Out-Download -Name $nm -InputObject $stream
              $stream.Close()
              $mediaStream.Close()
            }
    }

    $ZipPackage.Close()
}

BackupMediaItems


Enter fullscreen mode Exit fullscreen mode

Example:

This is an example with two images to backup:

Execute example to backup images

Thanks for reading!

I hope this script has been useful to you. If you have any questions or ideas in mind, it'll be a pleasure to be able to be in communication with you, and together exchange knowledge with each other.

X / LinkedIn - esdanielgomez.com

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay