Automating WSL2 VHDx Image Mount

On Feb 15th 2022, Mr. Fabio Akita released an awesome video about his daily driver setup and how he setup everything, just take a look.

But IMHO the key concept on this class, was about how to store your projects in a VHDx disk and use it in all your WSL distros.

WSL mount in a nutshell

Microsoft provides a utility to create, manage and reconfigure properties of your distro. With Windows 10/11 Professional and WSL 2 you can create, mount and attach virtual Hyper-V disks in your Linux WSL Virtual Machine.

Your easily mount and attach your virtual disk using this PowerShell single liner (in administrative mode)

1wsl --mount ("\\.\PhysicalDrive$((Mount-VHD -Path .\Projects-disk.vhdx -Passthru | get-disk).number)")
powershell

This command will mount your virtual disk with passthru option (Windows will not try to attach a drive letter or use it), extract the Disk Number, create the disk URI and finally mount it in the WSL 2 ecosystem at /mnt/wsl/PhysicalDrive<disk-number> folder, in all WSL 2 distros you installed in your Windows Professional box.

The problem

Besides mounting virtual disk only can be mounted in a Windows Professional installation (Mount-VHD cmdlet will be only available with full Hyper-V install), relay in disk numbers creates a faulty config dependency. Let me explain that.

This solution relays on disk numbers to create the disk URI, if you change your storage configuration like, add an USB Drive, SD Cards, your disk number will change. You made all configurations and automations expecting that your VHDx file will be mounted with drive number 8. At lunch time, your Windows starts a Windows Update restart, and you forgot an USB drive connected. And here we go, your mount point in all your Linux virtual machines are now PhisicalDisk9 instead PhisicalDisk8. You name all sort of problems, head scratches you got.

The solution

Microsoft provides Preview and Insiders versions of your products now. WSL 2 included. The Windows Subsystem for Linux 2 Preview (only available on Microsoft Store) adds lots of new configurations, parameters and functionalities, and the best one is named mount points.

Now you can customize the name a mount point when you mount a disk, partition, network share inside your WSL 2 virtual machines. To do this, just add water, I mean, --name option on the PowerShell one liner.

1wsl --mount ("\\.\PhysicalDrive$((Mount-VHD -Path .\Projects-disk.vhdx -Passthru | get-disk).number)") --name projects
powershell

Automagicly, WSL 2 will mount your disk at /mnt/wsl/projects in all your virtual machines, doesn’t matter the drive number your got. After that, just create a symbolic link to your home folder and voilà. Drive mounted and ready.

Hope this tip can add flexibility and make your workflow better!

Cheers,

Z

Comments