Backup WSL without using wsl --import or --export
Yes, Windows installs tend to wipe out user settings (i.e. AppData
), and the WSL files are typically installed there. Backing up the distribution is a good idea before performing a Windows reinstall. As you said, normally this would be done with wsl --export/--import
, but in your case, that's not viable.
For WSL2
Under WSL2, the entire filesystem is kept in a virtual HDD file named ext4.vhdx
. You can find it in %userprofile%\AppData\Local\Packages\CanonicalGroup...\LocalState\ext4.vhdx
. The ...
part will vary depending on the exact Ubuntu version you installed from the Store.
Back up this file before reinstalling Windows. Make sure WSL is not running at all via a wsl --shutdown
(assuming you can still access that command). If you can't wsl --shutdown
, at least reboot Windows before backing up the file, to make sure it is not in use. You could also run in safe mode, if you really want to be sure.
After reinstalling, you should be able to recover by:
- Reinstalling WSL (don't forget to set your default version to 2, if desired)
- Reinstalling Ubuntu from the Microsoft Store
- Copying back in the
ext4.vhdx
over the freshly installed one.
If you have Windows Professional or higher, it might also be wise to test the vhdx
by creating a new Ubuntu VM and attaching it (or preferably, a copy of the vhdx) as a drive.
I have copied vhdx's from one WSL installation over another before without issue, but of course there's no guarantee it's going to go perfectly.
Assuming that the vhdx
is valid, as a fallback you could mount it as a virtual drive in a VM, copy out the necessary user files, and copy just those over your new install.
For WSL1
For other readers who come across this and have WSL1 installations (perhaps in addition to WSL2), there's no way to back up and restore the entire filesystem as with WSL2.
But you can and should still backup the %userprofile%\AppData\Local\Packages\CanonicalGroup...\LocalState\rootfs
. This contains the entire filesystem, so any essential files can be copied back in to your new installation. However, it would not be safe to restore the entire filesystem from this backup, as permissions would have to be reset manually for every file/directory.
PLEASE NOTE that you should NEVER use this directory in anything but a dire case, such as the need to recover files when a WSL installation is completely borked. Accessing these files through Windows can result in a corrupted WSL installation according to Microsoft.