-
Notifications
You must be signed in to change notification settings - Fork 31
/
Compact-VHD.ps1
36 lines (30 loc) · 1.01 KB
/
Compact-VHD.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<#
.SYNOPSIS
Fully optimizes a Hyper-V VHD/X file.
.DESCRIPTION
Mounts the target VHD/X file as read-only, performs full optimization, and then dismounts it.
.NOTES
v1.0 January 28th, 2018
(c) 2018 Eric Siron
Source: https://www.altaro.com/hyper-v/compact-hyper-v-virtual-disks-vhdx/
#>
#requires -Module Hyper-V
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)][String]$Path,
[Parameter()][Microsoft.Vhd.PowerShell.VhdCompactMode]$Mode = [Microsoft.Vhd.PowerShell.VhdCompactMode]::Full
)
process {
try {
$Path = (Resolve-Path -Path $Path -ErrorAction Stop).Path
if ($Path -notmatch '.a?vhdx?$') { throw }
}
catch {
throw('{0} is not a valid VHDX file.' -f $Path)
}
Write-Host "Compact-VHD: $(([System.IO.FileInfo]$Path).Name) ..." -NoNewline
Mount-VHD -Path $Path -ReadOnly -ErrorAction Stop
Optimize-VHD -Path $Path -Mode $Mode -ErrorAction Continue
Dismount-VHD -Path $Path
Write-Host -ForegroundColor Green " Done."
}