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
Example:
This is an example with two images to backup:
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.
Top comments (0)