Using TimeMachine to back up to a Windows share

Apple’s TimeMachine provides a really easy way of backing up to an external hard drive, or an Apple-made TimeCapsule on your network. If you want to back up to a non-Apple drive on your network – for example a Windows share – it’s not so straight forward.
In short, what we do is create a sparseimage and copy it to the Windows share mounted on our Mac. Next, we mount that sparse image on the Mac and set it as our TimeMachine disk. Let’s look at that in more detail.
Create the sparseimage
hdiutil create -size 500g -type SPARSEBUNDLE -fs "HFS+J" ~/Desktop/TimeMachine.sparsebundle
The 500g bit sets the size of the sparseimage (in Gb). It needs to be at least as big as the Mac’s hard drive, but give it as much as you can on your Windows share.
Set up TimeMachine
sudo tmutil setdestination /Volumes/TimeMachine
What could possibly go wrong?
There are two potential gotcha’s here. The first one is that backups will only happen when the Time Machine share is visible. You *could* just remember to connect to the Windows share and double click the sparseimage to mount it every time you restart your Mac. If you’re forgetful like me then you can do it automatically with an AppleScript
try
mount volume "smb://path/to/your/windows/share"
end try
do shell script "hdiutil attach -mountpoint /Volumes/nameofwindowsshare/ /Volumes/nameofyourwindowsshare/TimeMachine.sparsebundle"
…simply paste this into a Script Editor window, and select save as Application. Add the saved application to your login items (System Preferences>Users & groups) so it mounts the sparseimage automatically on login.
The second gotcha is that if you need to rebuild your whole Mac (as opposed to just restore files from a particular date) for example after a hard disk failure then you can’t use OS X Recovery. You’ll need to install OS X from scratch, mount the Windows share and sparseimage then use Migration Assistant. Not particularly difficult, but worth making a note of to save you a panic!