清理Hyper-V R2未使用的vhd和快照文件?

我们正在使用Hyper-V R2作为虚拟化开发和testing环境的平台。

经过一个月的使用后,随着许多虚拟机的创build/删除,vhd商店里充满了大量的vhd和avhd文件。 其中一些是删除虚拟电脑的驱动器。

我如何清理虚拟驱动器文件夹?

是否有任何命令行(PowerShell的?)比枚举所有虚拟计算机的磁盘绑定(所以我可以删除除此列表以外的所有)?

[编辑]有点进步

我可以列出所有的虚拟机定义的XML文件,并分析控制器部分:

<controller0> <drive0> <pathname type="string">V:\Hyper-V\Virtual Hard Disks\my_computer_7679176A-F7AE-4D40-AC28-67FFDE7E2FEB.avhd</pathname> <type type="string">VHD</type> </drive0> <drive1> <pathname type="string">V:\Hyper-V\Virtual Hard Disks\my_computer_60892A6B-6AB4-44D7-8F08-509BF0E70A05.avhd</pathname> <type type="string">VHD</type> </drive1> </controller0> 

但是,由于计算机可以拥有快照,因此只能枚举所连接的磁盘,而不是其父节点所在的磁盘。

经过一番挖掘,我用这个方法:

首先,获取所有虚拟机的所有磁盘(我的服务器是法文的,你应该用英文系统的“硬盘”replace“Disque dur”):

 $disks = Get-vm | Get-VMDisk | ? { $_.DriveName -Match "disque dur" } 

然后,我提取所有的VHDpath:

 $vhds = @() $disks | % { Get-VHDInfo $_.DiskPath } | % { $vhds+= $_.Path } $vhds = $vhds | select -unique write-host $vhds.Length -Foreground Yellow 

最后,我根据需要经常运行以下代码。 当arrays的长度停止增长时,我停下来:

 $disks | % { Get-VHDInfo $_.DiskPath } | select ParentPath | ? {$_.ParentPath.Length -Gt 0} | % { $vhds+= $_.ParentPath } $vhds = $vhds | select -unique write-host $vhds.Length -Foreground Yellow $vhds | % { Get-VHDInfo $_ } | select ParentPath | ? {$_.ParentPath.Length -Gt 0} | % { $vhds+= $_.ParentPath } $vhds = $vhds | select -unique write-host $vhds.Length -Foreground Yellow #Repeat while Length grows 

最后, $vhds包含所有使用的驱动器及其父母。 只需枚举所有的.vhd和.avhd文件,并减去$ vhd数组find无用的磁盘。

我知道这可以重写一个很好的脚本,但它解决了我的问题。

这些cmdlet包含在Windows Server 2012中,是针对以前的操作系统的单独下载 。