Cover image for WSL空间压缩

WSL空间压缩


时间轴

时间轴

2025-12-29

init

本文介绍了压缩WSL发行版虚拟磁盘空间的具体方法,详细说明了在关闭WSL后,通过查找发行版磁盘文件路径并利用diskpart工具执行磁盘压缩操作的步骤。

.vhdx文件的磁盘路径

把distribution-name替换成通过wsl -l -v看到的发行版的名称

1
2
3
4
5
6
wsl -l -v

(Get-ChildItem -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss | Where-Object { $_.GetValue("DistributionName") -eq '<distribution-name>' }).GetValue("BasePath") + "\ext4.vhdx"

# 以archlinux为例
(Get-ChildItem -Path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss | Where-Object { $_.GetValue("DistributionName") -eq 'archlinux' }).GetValue("BasePath") + "\ext4.vhdx"

压缩磁盘

压缩前先关闭wsl

1
wsl --shutdown

然后输入diskpart

1
diskpart

此时弹出一个新的命令行窗口,依次输入下面内容,其中file的值替换成上面一步得到的路径

1
2
3
4
5
6
7
8
9
10
# 选择目标磁盘文件
select vdisk file="/path/to/your/.vhdx"
# 以只读模式连接虚拟磁盘文件
attach vdisk readonly
# 压缩虚拟磁盘文件
compact vdisk
# 分离虚拟磁盘文件
detach vdisk
# 退出
exit

参考