В случае, если вам потребовался доступ из Windows к данным на разделе диска с файловой системой Linux — ext4/ext3/ext2, встроенными средствами системы сделать это не получится. Однако, возможности есть, причем реализовать это можно встроенными средствами системы или с помощью сторонних инструментов.
В этой инструкции подробно о способах подключить раздел диска в файловой системе Linux в Windows 11 и Windows 10 для доступа к данным на этом разделе как для чтения, так и для записи.
Ext2 File System Driver (Ext2Fsd) — самый простой способ открыть раздел ext4/ext3/ext2 в Windows
Ext2 File System Driver или Ext2Fsd — сторонний и полностью бесплатный драйвер для подключения разделов Linux во всех версиях Windows начиная с XP. Несмотря на название, поддерживаются не только разделы не только с файловой системой ext2, но и более новые ext4 и ext3.
Порядок использования Ext2 File System Driver для доступа к дискам Linux будет следующим:
- Загрузите установщик Ext2Fsd с сайта https://sourceforge.net/projects/ext2fsd/
- Установите драйвер, в параметрах установки как правило не требуется ничего изменять.
- По завершении установки вам будет предложено запустить Ext2 Volume Manager (менеджер томов), запустите его.
- Нажмите правой кнопкой мыши по разделу Linux ext4, ext3, ext2 и выберите пункт «Assign Drive Letter» — назначить букву диска.
- Для раздела будет автоматически назначена буква диска, и вы увидите раздел в Проводнике Windows с возможностью чтения и записи файлов на нём.
В дальнейшем вы тем же способом сможете удалить букву диска с раздела (опция «Change letter» — «Remove»).
Доступ к разделам Linux средствами Подсистемы Windows для Linux (WSL)
Подсистема Windows для Linux (WSL) также может быть использована для подключения дисков Linux в Windows таким образом, чтобы доступ к ним был возможен из проводника. Шаги будут следующими:
- Запустите командную строку, Терминал или PowerShell от имени администратора и по порядку введите команды
wsl --install wsl --set-default-version 2 dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart wsl --install -d Ubuntu
- После выполнения последней команды откроется окно консоли Linux (командную строку при этом не закрывайте, она еще пригодится) с предложением настроить имя пользователя и пароль, сделайте это. Если в окне консоли вы увидите сообщение об ошибке, скачайте и установите обновление WSL, перезагрузите компьютер и запустите Ubuntu из меню «Пуск».
- В консоли Ubuntu введите команду
sudo mkdir -p /mnt/ext-drives/
для создания папки, к которой будут монтироваться диски.
- В консоли Windows (командная строка, терминал, Powershell) введите команду
wmic diskdrive list brief
- Обратите внимание на DeviceID диска, который нужно подключить и введите команду (так же в консоли Windows) указав соответствующий номер в имени PHYSICALDRIVE
wsl --mount \\.\PHYSICALDRIVE
- В консоли Ubuntu введите команду lsblk — это отобразит список подключенных дисков, разделов на них и их размер. В следующей команде используем имя нужного раздела для монтирования:
sudo mount /dev/sdИМЯ /mnt/ext-drives/
- После успешного выполнения всех указанных шагов вы можете зайти в Проводник Windows, выбрать пункт «Linux» в панели быстрого доступа, перейти в папку mnt\ext-drives и получить доступ к файлам на подключенном разделе Linux с возможностью записи и чтения.
В дальнейшем для отключения диска от WSL можно использовать ту же команду, которая использовалась на 5-м шаге, заменив mount на unmount.
Есть и другие программы (драйверы) для доступа к разделам Linux из Windows, но не полностью бесплатные. Среди них:
- DiskInternals Linux Reader — в бесплатной версии доступно только чтение данных с разделов.
- Paragon Linux File Systems for Windows — бесплатная работа в течение пробной версии, затем необходимо приобретать лицензию.
If you work with dual systems on your computer, combining Windows y Linux, surely you have ever faced the frustration of not being able to easily access partitions Linux from your operating system Windows. Although Linux has the ability to read and write to partitions NTFS de Windows, the reverse is usually not so simple.
Fortunately, there are different Tricks and tools that will allow you to access partitions Linux from Windows without any complicated configurations. We will explore the best ways to achieve this, from native methods to specialized applications.
What are Linux partitions and how do they work?
The partitions Linux They use file systems like EXX4, EXX3 o EXT2, designed to optimize the storage and data management in this operating system. Unlike file systems NTFS o FAT32 used by Windows, these partitions are not natively recognized by the system. MicrosoftThis can be inconvenient if you need to access your data Linux from Windows.
The system EXT4, for example, is the standard in most popular distributions such as Ubuntu o Debian. It offers advantages such as superior handling of large volumes of data and greater stability. However, as it is not compatible with Windows, requires external solutions to make your data accessible.
Native Methods: Windows Subsystem for Linux (WSL)
One of the most modern ways to access partitions Linux from Windows is to take advantage of the Windows Subsystem for Linux (WSL), available in the latest versions of Windows 10 y 11. This system not only allows you to run command line tools Linux, but also mount partitions of this operating system.
To enable WSL, follow these steps:
- Open the search box Windows and writes «Characteristics of Windows«. Select the option «Activate or deactivate features of Windows«.
- Find and check the option “Subsystem” Windows for Linux«. Click OK and restart your computer.
After enabling WSL, you can install a distribution like Ubuntu through Microsoft Store. Once installed, use commands , the wsl --mount
to mount your partitions Linux and access your data from the file explorer Windows.
Third-party applications to access Linux partitions
If WSL is not enough or you prefer a more direct solution, there are several specialized applications that will help you access partitions. Linux from WindowsLet’s look at the most popular ones:
LinuxReader
LinuxReader It is a free tool developed by Disk InternalsIts intuitive design allows you to explore partitions of Linux as if they were normal folders in Windows. It offers a very friendly visual interface for beginner users.
- Supports file systems EXT2, EXT3 y EXT4.
- Read-only, preventing accidental changes to data.
- Includes additional features such as exporting files to servers FTP.
To get started, download and install LinuxReader from their official page. Once you run it, it will automatically detect the partitions Linux and you will be able to explore its contents.
Ext2Fsd
Another effective tool is Ext2Fsd, a driver that allows mounting partitions EXT2, EXT3 y EXT4 directly in the file system Windows. Unlike LinuxReader, Ext2Fsd provides support for reading and writing.
- Configure auto-mounting for specific partitions.
- Allows you to assign drive letters to partitions Linux.
- Compatible with 32-bit and 64-bit systems.
To use Ext2Fsd, download it from their page at SourceForge, install it and configure it to mount partitions automatically at system startup. Remember to enable writing with caution, as you may damage data if you are not sure what you are doing.
Other useful programs
In addition to LinuxReader y Ext2Fsd, there are other recommended tools to access partitions Linux from Windows:
Disk Genius
Disk Genius is a powerful partition management tool that allows you to access file systems EXT, backup and recover data. Although some advanced features require a fee, the free version is ideal for basic uses.
Ext2Explore
Ext2Explore It is a portable application that does not require installation. Its main use is to allow the reading of partitions EXT, although it does not support modifications.
Protect your data when working with Linux partitions
It is important to be aware of certain risks when using tools to access file systems. Linux from WindowsSome programs allow writing, which can lead to errors or data corruption if not used correctly. Therefore, follow these recommendations:
- Make regular backups of your important data.
- Use tools that offer read-only access if you are unsure of your actions.
- Avoid modifying partitions while using them on non-native systems.
With these tools and methods, access your partitions Linux from Windows will be much simpler and safer. Whether you need to transfer files or perform advanced tasks, there is a solution tailored to your needs.
Passionate writer about the world of bytes and technology in general. I love sharing my knowledge through writing, and that’s what I’ll do on this blog, show you all the most interesting things about gadgets, software, hardware, tech trends, and more. My goal is to help you navigate the digital world in a simple and entertaining way.
Windows Subsystem for Linux (WSL) предоставляет ряд удобных возможности подключения физических, виртуальных и сетевых дисков. По умолчанию в среде wsl в каталог
/mnt/
монтируются все логические диски, которые доступны в Windows. Кроме того, вы можете прямо из проводника Windows обратиться к файловой системе WSL по UNC пути
\\wsl$\
(например,
\\wsl$\ubuntu\etc\
).
В этой статье мы рассмотрим, как смонтировать различные типы дисков в среде WSL.
Содержание:
- Монтирование физических дисков Windows Subsystem for Linux 2
- Как подключить (смонтировать) сетевой диск в WSL
- Смонтировать виртуальный VHD/VHDX диск в WSL
Монтирование физических дисков Windows Subsystem for Linux 2
Новая версия Windows Subsystem for Linux (WSL 2) позволяет монтировать физические диски, или отдельные разделы с файловыми системами, которые не поддерживаются в Windows (список поддерживаемых файловых систем содержится в файле
/proc/filesystems
).
Например, у вас есть физический на которым созданы разделы с файловой системой диск ext4, и вы хотите получить к нему доступ из WSL и Windows.
Обновите свою версию WSL 2, прежде чем двигаться дальше:
wsl --update
Теперь нужно вывести список доступных дисковых устройств в Windows:
wmic diskdrive list brief
В этом примере к компьютеру подключены два физических диска.
Можно смонтировать в WSL диск целиком:
wsl --mount \\.\PHYSICALDRIVE2
Или только определенный раздел:
wsl --mount \\.\PHYSICALDRIVE2 --partition 1
Раздел физического диска был успешно смонтирован в директорию /mnt/wsl/PHYSICALDRIVE2p1.
Вы можете получить доступ к файлам на этом разделе из Windows по UNC пути
\\wsl$\ubuntu\mnt\wsl\PHYSICALDRIVE2p1
.
Проверьте, что раздел диска с файловой системой ext4 доступен в WSL:
lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT
Чтобы отмонтировать диск, выполните:
wsl --umount \\.\PHYSICALDRIVE2 --partition 1
Для автоматического монтирования раздела физического диска при входе пользователя в Windows, создайте с помощью PowerShell простое задание планировщика:
$TaskName="WSL_Mount"
$Trigger= New-ScheduledTaskTrigger -AtLogOn
$Action= New-ScheduledTaskAction -Execute "cmd" -Argument "/c wsl --mount \\.\PHYSICALDRIVE2 --partition 1"
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -RunLevel Highest –Force
На данный момент WSL не поддерживает монтирование USB накопителей и SD карт. Для проброса USB накопителей в WSL рекомендуется использовать пакет usbipd-win, который позволяет реализовать проброс устройств с помощью протокола USB over IP.
Как подключить (смонтировать) сетевой диск в WSL
Из WSL вы можете получить доступ к общим сетевым папкам или NAS устройствам.
Есть два способа подключения сетевых дисков в WSL:
- Можно смонтировать сетевой диск, подключенный в Windows и которому назначена буква диска
- Смонитировать сетевую папку по UNC пути с помощью CIFS/SMB клиента в WSL.
Допустим, вы подключили сетевую папку в виде диска с помощью команды net.exe use X: \\192.168.31.102\tools или подключили сетевой диск через GPO. Чтобы получить доступ к этому сетевому диску из WSL нужно:
- Создать точку монтирования:
$ sudo mkdir /mnt/x
- Смонтировать диск:
$ sudo mount -t drvfs X: /mnt/x
- Теперь вы можете получить доступ к файлам и папкам на сетевом диске.
Чтобы автоматически монтировать этот сетевой диск, добавьте следующую строку в /etc/fstab:
X: /mnt/x drvfs defaults 0 0
Затем смонтируйте все файловые системы:
$ mount -a
Также можно смонтировать сетевые папки через пакет CIFS:
$ sudo apt install cifs-utils
$ sudo mount -t cifs -o user={user},pass={password},iocharset=utf8,vers=3.0 //192.168.31.102/tools /mnt/tools
Смонтировать виртуальный VHD/VHDX диск в WSL
WSL позволяет смонтировать виртуальные диски в форматах VHD/VHDX.
Если на компьютере установлен роль или PowerShell модуль Hyper-V, вы можете создать новый виртуальный диск с помощью команды:
New-VHD -Path $env:USERPROFILE\wsl_shared_disk.vhdx -Dynamic -SizeBytes 20GB
Затем смонтируйте виртуальный VHDX диск в WSL:
wsl --mount --vhd $env:USERPROFILE\wsl_shared_disk.vhdx --bare
Теперь вы можете создать на виртуальном диске таблицу разделов и раздел с файловой системой ext4:
$ lsblk
$ sudo parted /dev/sdc print
$ sudo parted /dev/sdc mklabel msdos
$ sudo parted -a optimal /dev/sdc mkpart primary ext4 0% 100%
$ lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT /dev/sdc
$ sudo mkfs.ext4 /dev/sdd1
Чтобы смонтировать новый раздел в определенную директорию, нужно получить его UUID;
$ sudo blkid
$ sudo mount UUID= 506f6faa-1f50-4763-b8a1-975f2b1c59fe /home/sysops/vhdx
Этот способ позволит смонтировать виртуальные диски других сред Linux, которые установлены на этом компьютере под WSL. Файловая система образов Linux WSL хранится в виртуальных дисках ext4.vhdx в папке
C:\Users\[user]\AppData\Local\Packages\[distro]\LocalState\[distroPackageName]
. Если на системном диске недостаточно места, можно перенести vhdx файл с файловой системой образа WSL на другой диск.
If you use Linux and Windows in your life, you’ll notice one huge point of frustration: Windows can’t read Linux partitions, which are typically in ext4 or ext3 file format. If you connect an external drive or microSD card that has a partition which is formatted in ext4 to your Windows PC, the OS won’t assign a drive letter to that partition or show you the files and folders.
The lack of ext4 / ext3 support is a particularly big problem for Raspberry Pi fans. When you install Raspberry Pi OS on a microSD card or external SSD to use as your boot disk, the drive has two partitions: a small boot partition that’s FAT32 and therefore visible in windows and a larger partition that’s ext4 and contains all the data and apps.
So let’s say were setting up a retro gaming console on your Pi and wanted to copy a whole bunch of ROMS onto the ext4 partition. Or perhaps you are using a Raspberry Pi to power a web server or a media server and you want to copy all your files to the card from your Windows PC. You need a way to access Linux ext4 partitions from within Windows.
Unfortunately, neither Windows 11 nor 10 comes with a built-in way to access Linux partitions. There are some pricey or outdated third-party utilities for accessing ext4, but the best way is to use WSL (Windows Subsystem for Linux) , Microsoft’s free Linux virtual machine. Once you have a WSL VM set up for this task, you can use it to mount USB devices such as microSD card readers, SSD enclosures and Flash Drives and those drives then appear in WIndows Explorer so you can treat them like any other drive.
Surprisingly, the process of setting up ext4 drive mounting for the first time is pretty intense. By default, WSL does not support mounting drives with Linux partitions so you need to go through a process of installing a free utility that runs in PowerShell, grabbing a bunch of packages in your Linux VM (usually Ubuntu) and compiling a custom version of the WSL Linux kernel that has USB Mass Storage drivers enabled. I learned all of the steps in this process by following along with this great tutorial video from AgileDevArt (huge h/t to him).
Below, I’ll show you how to set up WSL so you can mount external drives and access Linux partitions from within Windows 11 or 10. It’s not difficult, but it does take a few steps.
What You Need: Accessing Linux Partitions in Windows
- WSL2 (Windows Subsystem for Linux) Installed (how to install WSL2)
- Ubuntu or some other Linux flavor installed under WSL2, available here.
- PowerShell 7 or higher. You can get it here.
- microSD card with USB card reader or USB Flash drive with ext4 partition
How to Read / Write Linux Ext4 Partitions in Windows
1. Download and install usbipd. You can get the latest release on Github or type «winget install usbipd» from within PowerShell.
Get Tom’s Hardware’s best news and in-depth reviews, straight to your inbox.
2. Launch Powershell 7 as Administrator.
3. Update WSL to the latest Linux kernel by typing wsl —update in PowerShell. If you already have the latest version, it will say so.
4. Launch Ubuntu in Windows.
5. Update and Upgrade your packages with these commands. The -y switch will auto-accept the installation of any new packages.
sudo apt-get update
sudo apt-get upgrade -y
6. Enter uname -a to determine what version of the Linux kernel you have. Take note of the exact version number. In our case, that was 5.15.153.1.
7. Assign the version number to an environment variable called VER.
VER=5.15.153.1
8. Install some required packages with this command. The -y switch will auto-accept the installation of the required packages.
sudo apt install -y build-essential flex bison libgtk2.0-dev libelf-dev libncurses-dev autoconf libudev-dev libtool zip unzip v4l-utils libssl-dev python3-pip cmake git iputils-ping net-tools dwarves usbutils
9. Clone the kernel source from Github and change into its directory with the following command.
sudo git clone -b linux-msft-wsl-${VER} https://github.com/microsoft/WSL2-Linux-Kernel.git ${VER}-microsoft-standard && cd ${VER}-microsoft-standard
Note that the kernel source will take several minutes to download. When it is done, you will be in the new directory it created (ex: 5.15.153.1-microsoft-standard).
10. Copy the config.gz file to the current directory and unzip it to filename .config.
sudo cp /proc/config.gz config.gz && sudo gunzip config.gz && sudo mv config .config
11. Enter sudo make menuconfig to open the modules menu.
sudo make menuconfig
You will now see a GUI menu. We recommend stretching your Ubuntu window out so you can see more of it.
12. Navigate to Device Drivers -> USB support
13. Select USB Mass Storage Support and hit Y to put an * next to it.
14. Select Exit on the bottom of the screen (using the Tab key) multiple times until you get asked to save.
15. Select Yes when asked to save.
16. Enter the following make commands, one after the other. This process will take a few minutes.
sudo make -j$(nproc)
sudo make modules_install -j$(nproc)
sudo make install -j$(nproc)
17. Copy the vmlinux file to your user folder in windows. Replace [USERNAME] in the example below with your Windows user folder. For example my account is «avram» or /mnt/c/users/avram.
sudo cp -rf vmlinux /mnt/c/users/[USERNAME]
18. Change directory to your Windows user directory.
cd /mnt/c/users/[USERNAME]
19. Open / create a text file in that directory called .wslconfig. Use nano to edit the file from within Ubuntu.
sudo nano .wslconfig
20. Enter the following text in the .wslconfig file and save it. Replace [USERNAME] with the correct folder name that matches your username. In my case, it was C:\\users\\avram\\vmlinux.
[wsl2]
kernel=C:\\users\\[USERNAME]\\vmlinux
21. Close Ubuntu.
22. Shut down wsl by typing wsl —shutdown in PowerShell.
23. Open Ubuntu.
24. In Powershell (opened as admin), list all available drives by typing usbipd list.
Take note of the BUSID number of the USB Mass Storage Device, which is likely the USB disk you want to mount. In our case, the ID was 1-2.
25. Bind the drive by entering usbipd bind —busid=[BUSID], replacing [BUSID] with the actual ID on the list. In our case, it was usbipd bind —busid=1-2.
26. Attach the drive to wsl by entering usbipd attach —wsl —busid=[BUSID]
27. In Ubuntu, enter lsblk to see a list of drives. If everything worked, you’ll see your Flash drive / microSD card on the list. In the case of a Raspberry Pi microSD card, there will be two partitions listed. The first one is the /boot partition which is FAT and readable by Windows natively, but the second one is ext4.
On our system, the partitions on the microSD card were assigned as sdd1 and sdd2.
28. Make folders in Ubuntu for mounting your partition(s) using mkdir and placing them under the /mnt directory. For example, we made /mnt/raspi but you could call your folder anything as long as it’s under /mnt.
sudo mkdir /mnt/raspi
29. Use the mount command to mount your partition to the folder you created. Replace [PARTITION] with the actual partition name (ex: sdd2) and [FOLDER] with the one you created. In our case, this was sudo mount /dev/sdd2 /mnt/raspi.
sudo mount /dev/[PARTITION] /mnt/[FOLDER]
30. Make the partition writable by using chmod 777. In our case, it was sudo chmod 777 /mnt/raspi. The chmod 777 command will make the partition readable and writable by any user. Typically this is a bad security practice, but in this case it is viable given that we’re not working in a secure environment.
sudo chmod 777 /mnt/[FOLDER]
31. Locate the folder in Windows Explorer. It should be under Linux->Ubuntu->mnt. If you have a specific version of Ubuntu installed (in our case 24.04 LTS), it will be under that name instead of just Ubuntu. If you have a different version of Linux installed in WSL2, it will be under that.
You can now read from and write to that partition from Windows Explorer. You can close the Ubuntu window if you want or you can use the Ubuntu command line to copy files instead of using Windows Explorer.
The next time you want to mount a drive with ext4 on it, you simply need to use PowerShell and follow steps 23 to 31 to get it to show up in Windows Explorer. If you have an existing USB drive you have already mounted once and you unplug it and then plug it back in, it should continue to be available, at least if you haven’t shut down wsl and PowerShell.
Windows OS Hub / Windows 11 / Mount Physical and Network Drives in WSL2 (Windows Subsystem for Linux)
There are several ways to mount and access physical, virtual, or network drives in Windows Subsystem for Linux (WSL2). By default, the WSL environment mounts all Windows logical drives to the /mnt/
directory. In addition, you can access the WSL file system directly from File Explorer running on the Windows host by using the UNC path \\wsl$\
(for example, \\wsl$\ubuntu
).
This guide explains how to mount different drives in a WSL environment.
Contents:
- How to Mount Physical Drive (Partition) in WSL2
- Mounting Windows Network Drives in WSL
- Attach Virtual Hard Drive (VHD/VHDX) in WSL
How to Mount Physical Drive (Partition) in WSL2
Windows Subsystem for Linux (WSL 2) makes it possible to mount physical drives or specific partitions with file systems that are not supported by the Windows host itself. The /proc/filesystems
file contains the list of supported filesystems in WSL.
For example, you have a physical disk with ext4 partitions on it and you want to access them from WSL.
Before proceeding, check and update your WSL 2 version:
wsl --update
Then list the available disk devices in Windows:
wmic diskdrive list brief
Two physical disks are connected to the computer in this example.
You can mount an entire hard disk drive in the WSL:
wsl --mount \\.\PHYSICALDRIVE2
Or just a specific partition:
wsl --mount \\.\PHYSICALDRIVE2 --partition 1
The partition of the physical hard disk will be mounted in the directory /mnt/wsl/PHYSICALDRIVE2p1.
You can access files on this partition from a Windows host using a UNC path: \\wsl$\ubuntu\mnt\wsl\PHYSICALDRIVE2p1
.
Check that the ext4 filesystem partition is accessible in WSL:
$ lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT
To unmount the partition, run:
wsl --umount \\.\PHYSICALDRIVE2 --partition 1
To automatically mount a physical disk partition when a user logs on to Windows, create a simple scheduler task using PowerShell:
$TaskName="WSL_Mount_DISK1_PART1"
$Trigger= New-ScheduledTaskTrigger -AtLogOn
$Action= New-ScheduledTaskAction -Execute "cmd" -Argument "/c wsl --mount \\.\PHYSICALDRIVE2 --partition 1"
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -Action $Action -RunLevel Highest –Force
WSL 2 doesn’t currently support the mounting of USB drives or SD cards. To attach USB storage devices to WSL, it is recommended to use the usbipd-win package (allows to passthrough external USB devices using the USB over IP protocol).
Mounting Windows Network Drives in WSL
In WSL, you can access shared folders on network computers or NAS devices. There are two ways to mount network drives in WSL:
- You can mount a network drive that is mapped in Windows and has a drive letter assigned to it.
- It is possible to use the CIFS/SMB client in WSL to mount a shared network folder using a UNC path.
For example, you have mapped a network drive using GPO or with the net use X: \\192.168.100.12\tools
command. To access this network drive from WSL:
- Create a mount point:
$ sudo mkdir /mnt/x
- Mount the drive:
$ sudo mount -t drvfs X: /mnt/x
- Now you can access files and folders on the network drive.
To automatically mount this network drive, add the following line to /etc/fstab:
X: /mnt/x drvfs defaults 0 0
Then mount all the file systems:
$ mount -a
Shared network folders can also be mounted directly from SMB-enabled devices using the CIFS package.
$ sudo apt install cifs-utils
$ sudo mount -t cifs -o user={user},pass={password},iocharset=utf8,vers=3.0 //192.168.100.12/tools /mnt/tools
This example uses the SMB 3.0 protocol to connect to shared folders instead of SMBv1 which is disabled by default in current versions of Windows.
Attach Virtual Hard Drive (VHD/VHDX) in WSL
VHD/VHDX virtual hard disks can also be mounted with WSL. If the Hyper-V PowerShell module is installed on the computer, create a new virtual disk file using the command:
New-VHD -Path $env:USERPROFILE\wsl_shared_disk.vhdx -Dynamic -SizeBytes 20GB
Then mount the VHDX file in WSL:
wsl --mount --vhd $env:USERPROFILE\wsl_shared_disk.vhdx --bare
Now you can create a partition table and a partition with the ext4 file system on the virtual disk:
$ lsblk
$ sudo parted /dev/sdc print
$ sudo parted /dev/sdc mklabel msdos
$ sudo parted -a optimal /dev/sdc mkpart primary ext4 0% 100%
$ lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT /dev/sdc
$ sudo mkfs.ext4 /dev/sdd1
Then you can mount a new partition to a directory by its UUID:
$ sudo blkid
$ sudo mount UUID=c04d0309-b93a-47f2-ae0d-79c95c80cd51 /home/sysops/vhdx
Using this method, you will be able to mount the virtual hard disks of other Linux environments that are installed on this computer under WSL. The Linux WSL image file system is stored in the ext4.vhdx
virtual disk in the C:\Users\[user]\AppData\Local\Packages\[distro]\LocalState\[distroPackageName]
folder. If you don’t have enough free space on the system drive, you can move the VHDX file that contains the WSL image file system to another drive.