
param(
    [Parameter(Mandatory = $true)]
    [string]$VHDxPath
)
    
$VHDx = Get-VHD -Path $VHDxPath
$sizeBeforeOptimization = (Get-Item $VHDxPath).Length / 1MB
if($VHDx.Attached)
{
    Write-Host "Disk is already attached"
    if((Get-WindowsFeature -Name "Hyper-V").InstallState -eq "Installed")
    {
        $isAttachedToAnyVM = $false
        $isAttachedToAnyVM = 
            Get-VM | 
            Select-Object -Property VMId | 
            Get-VHD -ErrorAction SilentlyContinue | 
            ForEach-Object { if($_.Path -eq $VHDxPath) { return $true }}
        if($isAttachedToAnyVM)
        {
            Write-Host "Disk is attached to a VM"
            exit 1
        }
    }

    $driveLetter = (Get-VHD -Path $VHDxPath | Get-Disk | Get-Partition | Get-Volume | Select-Object DriveLetter).DriveLetter
}
else {
    Write-Host "Disk is not attached"
    $driveLetter = (Mount-VHD -Path $VHDxPath -Passthru | Get-Disk | Get-Partition | Get-Volume | Select-Object DriveLetter).DriveLetter
}
Write-Host $driveLetter

$featureName = "FS-Data-Deduplication"
$volume = "${driveLetter}:"
$minimumFileSizeB = 1024*1024 # 1 MiB
if((Get-WindowsFeature -Name $featureName).InstallState -ne "Installed") 
{ 
    Install-WindowsFeature -Name $featureName -IncludeAllSubFeature
    Write-Host "Installing $featureName"
}

try {
    Get-DedupVolume -Volume $volume -ErrorAction Stop
}
catch {
    Enable-DedupVolume -Volume $volume -ErrorAction Stop
}
Set-DedupVolume -Volume $volume -NoCompress $true -MinimumFileAgeDays 0 -MinimumFileSize $minimumFileSizeB
Start-DedupJob -Type Optimization -Volume $volume -Priority High -Wait
Dismount-VHD -Path $VHDxPath

Optimize-VHD -Path $VHDxPath -Mode Full -ErrorAction Stop
$sizeAfterOptimization = (Get-Item $VHDxPath).Length / 1MB
Write-Host "Before: $sizeBeforeOptimization MB | After: $sizeAfterOptimization MB"