Download Sitecore media items to local disk


BACK TO BLOG OVERVIEW


For one of our customers we were in need of downloading all media files from Sitecore to our local hard disk. Since we are using the Sitecore SPE extension, the following script gave us all the urls we needed to download them using our local Powershell.


[code language="powershell”] $url = “https://URLOFTHESITECOREWEBSITE/” $mediaLibraryRootPath = “master:/sitecore/media library/Images/” $listAllItems = Get-ChildItem -Recurse $mediaLibraryRootPath

foreach($item in $listAllItems){

$checkValue = $item.extension $checkValueForWhiteSpaceOrNull = [string]::IsNullOrWhiteSpace($checkValue)

if ($checkValueForWhiteSpaceOrNull -eq $true) { } else {

$replace = “\/sitecore/media library\/” $mediafolder = “/~/media/” $splitName = $item.fullPath $finalPath = $splitName -replace “$replace”, “$mediafolder”

Write-Host ($url + $finalPath + “.” + $item.extension) } } [/code]


Once you retrieve all the urls, use them in a local powershell session and execute the following script:


[code language="powershell”] [net.Servicepointmanager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12

$urls = “https://URLOFTHESITECOREWEBSITE/~/media/Images/CustomerExample/image1.png”, “https://URLOFTHESITECOREWEBSITE/~/media/Images/CustomerExample/image2.png”, “https://URLOFTHESITECOREWEBSITE/~/media/Images/CustomerExample/image3.jpg”

foreach ($url in $urls)

{ $downloadFolder = “C:\TMP\DownloadSitecoreMedia” $checkDownloadFolder = test-path ($downloadFolder + $filepath)

if (-not $checkDownloadFolder){ mkdir ($downloadFolder) } else { Write-Host “$downloadFolder directory already exists..skipping creation of directory.” }

$req = [System.Net.HttpWebRequest]::Create($Url) $req.Method = “HEAD” $response = $req.GetResponse() $fUri = $response.ResponseUri $filename = [System.IO.Path]::GetFileName($fUri.LocalPath); $filepath = [System.IO.Path]::GetDirectoryName($fUri.LocalPath); $response.Close() $checkDir = test-path ($downloadFolder + $filepath)

if (-not $checkDir){ mkdir ($downloadFolder + $filepath) } else { Write-Host “($downloadFolder + $filepath) directory already exists..skipping creation of directory.” }

$savefilename = $downloadFolder + $filepath + $filename

Invoke-WebRequest -Uri $url -usebasicparsing -OutFile $savefilename

} [/code]


By having all the media on your local hard drive it is just a few clicks with IrfanView to compress using batch conversion.