Recover Photos From a Formatted USB Stick With PowerShell, Python

Advertisement
Recover Photos From a Formatted USB Stick With PowerShell, Python Claude Code
Advertisement

I had a USB stick (1GB) that once held old pictures, then got reused many times: fill it with other data, format, repeat. Later I wanted those old pictures back.

I asked Claude Code “can you recover old data from a formatted USB stick?” and let it investigate. No dedicated recovery software: just PowerShell plus Python, already on the PC.

Short answer: 36 images came back (one missing its bottom half). Older images had been overwritten by data written later, so they were gone. A format alone can often be undone, but after writing data again many times, the older something is, the less likely it survives.

Below: how I copied the whole USB stick then carved images out of the copy, the scripts I used, the results.

First: write nothing to the USB stick

If you want to recover from a formatted USB stick, there’s one rule to follow first: don’t save files to it, don’t format it again. If Windows asks “Do you want to scan and fix?”, decline. Every write overwrites more of the old data still left.

I copied the entire contents of the stick into one file (an image file) on the PC’s D drive, then worked only on that copy. The stick itself was only ever read.

The type of format changes your chances

Windows has “Quick Format” plus the regular (full) format:

  • Quick Format: only rebuilds the file list (the map of what is where). The data itself is usually still there
  • Regular format: since Windows Vista, it writes zeros over the whole drive. Then the data can’t come back

That a regular format writes zeros everywhere is documented in Microsoft’s Change in the behavior of the format command in Windows Vista and later versions - Microsoft Learn. If “Quick Format” is checked in Explorer’s format dialog, no zeros are written.

I didn’t remember which I’d used. But examining the copy, 99.5% of sectors contained non-zero data. So at least the last format hadn’t zeroed the whole thing.

The USB stick’s state

As seen from PowerShell:

  • Capacity: about 1GB (1,039,859,712 bytes)
  • File system: FAT
  • Contents: only the System Volume Information folder Windows creates; otherwise empty

The commands I used (F is the stick’s drive letter):

Get-Volume -DriveLetter F | Format-List DriveLetter,FileSystem,DriveType,Size,SizeRemaining
Get-Partition -DriveLetter F | Format-List DiskNumber,Offset,Size

Step 1: save the whole USB stick as an image file

Opening the stick as \\.\F: lets you read it directly from start to end, bypassing the file list. The script writes that straight to a file, using Windows’ CreateFile read-only.

Paste this into PowerShell and run it. Save to a drive other than the USB stick. Feel free to use the scripts in this post.

$drive = 'F'
$out = 'D:\usb_recovery\usb.img'
$start = 0

$end = (Get-Partition -DriveLetter $drive).Size
New-Item -ItemType Directory -Force -Path (Split-Path $out) | Out-Null
Add-Type -TypeDefinition @"
using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles;
public static class RawCopy {
  [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
  public static extern SafeFileHandle CreateFile(string n, uint a, uint s, IntPtr sa, uint c, uint f, IntPtr t);
  public static string Dump(string dev, string outp, long start, long end) {
    var h = CreateFile(dev, 0x80000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
    if (h.IsInvalid) return "OPEN FAILED err=" + Marshal.GetLastWin32Error();
    long pos = start; long bad = 0;
    using (var fs = new FileStream(h, FileAccess.Read, 4096, false))
    using (var o = File.Create(outp)) {
      var buf = new byte[65536];
      while (pos < end) {
        int want = (int)Math.Min(buf.Length, end - pos);
        bool ok = false;
        for (int t = 0; t < 3 && !ok; t++) {
          try { fs.Position = pos; int n = fs.Read(buf, 0, want); if (n <= 0) return "EOF at " + pos + " bad=" + bad; o.Write(buf, 0, n); pos += n; ok = true; }
          catch (Exception e) {
            if (e.Message.Contains("does not exist")) return "DEVICE LOST at " + pos + " bad=" + bad;
            System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(200));
          }
        }
        if (!ok) {
          var sec = new byte[512];
          for (int i = 0; i < want; i += 512) {
            try { fs.Position = pos; fs.Read(sec, 0, 512); }
            catch (Exception e) {
              if (e.Message.Contains("does not exist")) return "DEVICE LOST at " + pos + " bad=" + bad;
              Array.Clear(sec, 0, 512); bad++;
            }
            o.Write(sec, 0, 512); pos += 512;
          }
        }
      }
    }
    return "OK end=" + pos + " badSectors=" + bad;
  }
}
"@
[RawCopy]::Dump("\\.\$($drive):", $out, $start, $end)

What to change for your setup:

What Where Example
Drive letter of the USB stick $drive F
Image file to save (not on the stick) $out D:\usb_recovery\usb.img
Where to start reading (bytes) $start 0 (use the stopping position to resume)

What it does:

  • The second argument to CreateFile, 0x80000000, means read (GENERIC_READ). Nothing is written to the stick
  • It reads 64KB at a time, retrying up to 3 times on failure. If that still fails, it reads 512 bytes at a time, filling unreadable parts with zeros, then moves on (the final badSectors is their count)
  • If the stick disconnects, it stops, printing how far it got as DEVICE LOST at …

Opening a volume as \\.\F: is described under “Physical disks, volumes” in CreateFileW function (fileapi.h) - Microsoft Learn. It says admin rights are required, but on my PC a non-admin PowerShell could read the stick. If you get OPEN FAILED err=5 (access denied), rerun PowerShell as administrator.

If the stick disconnects midway, resume from there

For me, the stick vanished from the PC after about 740MB (739,246,080 bytes). Whether it was a bad contact or a failing stick, I don’t know.

I reinserted it, confirmed it came back with the same drive letter, then read just the rest into a separate file. Change the first three lines of the script above like this, then run it again (put the stopping position into $start):

$drive = 'F'
$out = 'D:\usb_recovery\usb_part2.img'
$start = 739246080

This time it read to the end with OK end=1039859712 badSectors=0, so no unreadable parts. Combine the two files with copy /b in Command Prompt:

cd /d D:\usb_recovery
copy /b usb.img + usb_part2.img usb_full.img

copy /b combines files as binary (copy - Microsoft Learn). If the resulting usb_full.img is 1,039,859,712 bytes, same as the stick, combining worked.

Step 2: find and carve out JPEGs from the image file

The format erased the file list, so you can’t search by file name. Instead, look for images in the data itself. A JPEG always starts with the bytes FF D8 FF, ending with FF D9. Find those, then cut out what’s between as one image. This is called “file carving”.

A JPEG can contain a thumbnail, though, so the first FF D9 may be the end of the thumbnail. The script therefore walks the JPEG structure (each block’s length) to find the FF D9 after the main image data.

I used Python (3.14) with the imaging library Pillow. Install Pillow first if you don’t have it (Basic Installation - Pillow):

python -m pip install --upgrade Pillow

Save this as carve_jpeg.py. It’s what I actually used, tidied up for readability. For this English version I switched file reading and writing to pathlib and the image check to Pillow’s parser, then ran it again on a test image file to confirm the same results.

import re, struct, sys, os
from pathlib import Path
from PIL import ImageFile

img_path = sys.argv[1]
out_dir = sys.argv[2]
os.makedirs(out_dir, exist_ok=True)
data = Path(img_path).read_bytes()

NO_LENGTH = {0xD8, 0x01, *range(0xD0, 0xD8)}

def find_end(s):
    # Walk the JPEG structure to find the FF D9 after the image data
    p = s + 2
    while p + 4 <= len(data):
        if data[p] != 0xFF:
            return None
        m = data[p + 1]
        if m == 0xFF:
            p += 1
            continue
        if m in NO_LENGTH:  # SOI, TEM, RST0-7 have no length field
            p += 2
            continue
        length = struct.unpack('>H', data[p + 2:p + 4])[0]
        if m == 0xDA:
            q = data.find(b'\xff\xd9', p + 2 + length)
            return q + 2 if q >= 0 else None
        p += 2 + length
    return None

n = 0
for hit in re.finditer(rb'\xff\xd8\xff[\xe0\xe1\xdb\xee]', data):
    s = hit.start()
    e = find_end(s)
    if not e:
        print('skip', s)
        continue
    n += 1
    f = os.path.join(out_dir, f'img_{n:03d}_off{s}.jpg')
    Path(f).write_bytes(data[s:e])
    try:
        parser = ImageFile.Parser()
        parser.feed(data[s:e])
        parser.close().load()
        st = 'OK'
    except Exception as ex:
        st = 'NG ' + str(ex)[:50]
    print(n, s, e - s, st)
print('found:', n)

Run it like this. The first argument is the image file, the second the output folder.

cd /d D:\usb_recovery
python carve_jpeg.py usb_full.img recovered

Carved images are saved with names like img_001_off193802240.jpg. The number after off is the byte offset from the start of the stick. If the last column says OK, Pillow could load it as a complete image.

The script loads the whole image file into memory. Fine for a 1GB stick, but for tens of GB of USB or SD card, PhotoRec (below) is the better choice.

Results: 36 images back, the old ones gone

36 JPEGs were found. No other image formats such as PNG, GIF.

Item Result
Images found 36 JPEGs (about 0.3-0.8MB each)
Viewable 35
Partly missing 1 (top displays, bottom half gray)
Where they were Clustered in 3 places, about 190MB, 320MB, 335MB from the start
Beyond about 342MB Random-looking data to the end, with not a single image start (FF D8 FF)

File names, dates taken don’t come back: those lived in the file list the format erased. Also, if an image was stored in scattered pieces on the stick, this method can’t put them back together. The one missing its bottom half is probably that (not verified).

I couldn’t tell what was beyond 342MB. Possibly fragments of archives or videos. Either way, non-image data had been written there.

Why old images don’t survive repeated formatting

Quick Format erases only the file list; the data stays. But writing new data afterwards replaces whatever was in that spot. Overwritten data can’t be recovered by any software.

My stick had gone through “fill with other data, format” many times. The 36 images that came back are probably leftovers from the later rounds. The older images were most likely overwritten by data written afterwards. 99.5% of the stick was filled with data, leaving almost no untouched space.

USB sticks also have spare areas invisible to the PC. Old data could conceivably remain there, but reading it requires a lab removing the memory chip. I haven’t tried that.

Normally, just use the free PhotoRec

This time Claude Code wrote scripts on the spot, so no tools needed installing. But for the same job, the free recovery tool PhotoRec is easier. Its official description (PhotoRec - CGSecurity) says:

  • It ignores the file system, recovering photos, videos, documents etc. from the data itself, so it works on formatted drives
  • It treats the source drive as read-only; don’t save recovered files to the same drive
  • It supports FAT, NTFS, exFAT among others, running on Windows
  • It works on dd-made image files, not just the device itself
  • It’s open source (GPL), free

The idea is the same as my script, while PhotoRec handles many formats besides JPEG. The usb_full.img from step 1 is a raw copy (same as dd format), so PhotoRec should accept it. I haven’t tried PhotoRec.

Where to look if it isn’t on the stick

Images the stick couldn’t give back may be more likely found elsewhere:

  • Where the image was first saved (camera, phone, an old PC)
  • Cloud services like Google Photos, iCloud, OneDrive
  • Email or messaging history, if you ever sent them to someone
  • Old PCs, SD cards, external drives: the same steps work on them

Keep important data in more than one place, not on a single USB stick. I back up my D drive to a NAS; how is in Back up a local folder to a password-protected NAS with Robocopy.

Summary

  • To recover from a formatted USB stick, first write nothing to it
  • After Quick Format the data is often still there. A regular format on Windows Vista or later zeros the drive, so nothing comes back
  • I opened the stick as \\.\F:, copied it whole to an image file, then carved JPEGs out of the copy by finding FF D8 FF … FF D9
  • From a 1GB stick formatted, reused many times, 36 images came back (one missing its bottom half). Older images had been overwritten
  • PhotoRec does the same. File names, dates taken don’t come back

Comments

Copied title and URL