Monday, November 24, 2014

Windows Vista/7 Recycle Bin Recovery Script

Recently, I was presented with a laptop that had a non-functioning motherboard and asked if I could recover any files remaining on it.  Initially, I thought that it would be easy, just a matter of attaching the hard drive to another computer and copying the files off.  However, it turns out that in the process of the motherboard not working, Windows had decided to move all of the user documents to the Recycle Bin.

So, I set out to find how the Windows 7 Recycle Bin stores its files, since surely this person did not have a bunch of files all named $R247R2D, $I247R2D and so forth.  I came across this post describing the nature of the files, and where to uncover the original filename(s).  Now just to whip up something so that I don't have to look at each file individually.

Caveat: This is by no means the most elegant, compact, or precise way to do this, this is just the one-line bash script I used with some white space added for readability.

export RECYCLE_BIN="/path/to/$Recycle.Bin/userSID"
export RECOVER_PATH="/path/to/restore/files"
cd $RECYCLE_BIN
ls -ad \$R* | sed -e 's/^\$R//' |
while read f; do
  export ORIG_FILE="$(dd if=\$I$f bs=1 skip=24 2>/dev/null |
    iconv -f UTF16 -t UTF8 |
    sed -e 's/^[A-Z]:\\//' -e 's/\\/\//g')"
  
  mkdir -p "$RECOVER_PATH/$(dirname "$ORIG_FILE")"
  cp -pr \$R$f "$RECOVER_PATH/$ORIG_FILE"
done

To quickly describe the script, it takes every filename in the Recycle Bin location starting with $R, and then strips off the $R, since each file/folder to recover has both a $R and $I file with the same rest of the filename.  Then it skips 24 bytes into the metadata file (starting with $I) and outputs the rest of the binary file through iconv to convert the 16-bit Unicode characters back to 8-bit characters.  Then it strips off the drive letter from the Windows pathname, and then replaces all of the backslashes with forward slashes.

Once all of that is done, it finally has the original filename in a format it can work with.  The rest is simply creating the folder structure to receive the recovered file, followed by a copy back to its original filename.

You could have this script simply rename the files in-place rather than copying them to another location, or create soft links in another location.  All that is needed would be to change the cp line to something else that suites your recovery situation.

Enjoy!