2 minute read

As part of my migration from my old blogging software to new, I needed a way to snag all of the images. However, the old system stored the images as extension-less numbers, making it tedious to match article slug to image quickly. I pulled down a database extract with photo ID and slug, but needed a way to pull down the images and rename them from /{id} to /{slug}.{proper_extension} accordingly.

Time for some PowerShell.

Assumptions

  • I have a csv file with two columns in it: PhotoUrl and Slug. PhotoUrl provides the /path/to/file/{id} format and Slug provides the article slug that I’m migrating to the new blog.

  • Since the photo URLs are extensionless, I’ll need to detect what type of image they are and add the appropriate extension to the file.

The Script

# import the required modules
# note: I use bits to pull down the files, you can use webclient or your method of choice
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
import-module bitstransfer

# open csv for data
$csv = import-csv '.\blog.export.csv'

# create images directory
new-item -itemtype directory -path images -erroraction ignore

# download, detect, and rename files
foreach ($row in $csv) {
	try {	
		# download remote file to local file
		start-bitstransfer -source $row.PhotoUrl -destination (join-path '.\images\' $row.Slug)

		# output file name (and get full name for FileStream later)
		$outpath = (get-item (join-path '.\images\' $row.Slug)).FullName

		# open into image stream (to prevent locking the file)
		$fs = new-object IO.FileStream $outpath, 'Open','Read'
		$img = [System.Drawing.Image]::FromStream($fs)
		$format = $img.RawFormat
		$fs.Close()
		$img = $null

		# rename based on common extensions (add more if necessary)
		if ($format.Equals([System.Drawing.Imaging.ImageFormat]::Jpeg)) {
			rename-item -path $outpath -newname  $([io.path]::changeextension($outpath, "jpg"))
		} elseif ($format.Equals([System.Drawing.Imaging.ImageFormat]::Png)) {
			rename-item -path $outpath -newname $([io.path]::changeextension($outpath, "png"))
		}  elseif ($format.Equals([System.Drawing.Imaging.ImageFormat]::Gif)) {
			rename-item -path $outpath -newname $([io.path]::changeextension($outpath, "gif"))
		}
	} catch [OutOfMemoryException] {
		return;
	}
}
comments powered by Disqus