
param(
    [Parameter(Mandatory = $true)]
    [string]$VMName,
    [Parameter(Mandatory = $true)]
    [string]$AdminPassword
)

$password = ConvertTo-SecureString $AdminPassword -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("Administrator", $password)

$diskpartScriptFindVolume = @"
select disk 0
detail disk
"@

function RemoteExecuteDiskpartScript([string]$diskpartScript)
{
    $output = Invoke-Command -VMName $VMName -Credential $cred -ScriptBlock {
        param($diskpartScript)
    
        $diskpartScriptPath = "C:\AOFG\diskpartScript.txt"
        $diskpartScriptOutput = "C:\AOFG\diskpartOutput.txt"
        Set-Content -Path $diskpartScriptPath -Value $diskpartScript
        Start-Process -FilePath "diskpart.exe" -ArgumentList "/s $diskpartScriptPath" -Wait -RedirectStandardOutput $diskpartScriptOutput
        
        $output = Get-Content -Path $diskpartScriptOutput

        # Clean up the diskpart script file
        Remove-Item -Path $diskpartScriptPath
        Remove-Item -Path $diskpartScriptOutput

        return $output
    } -ArgumentList $diskpartScript
    return $output
}

$rawDiskInfo = RemoteExecuteDiskpartScript -diskpartScript $diskpartScriptFindVolume
$patternRecovery = "Volume\s+(\d+).*Hidden"
$recoveryVolumeNumber = ($rawDiskInfo | Select-String -Pattern $patternRecovery)
$recoveryVolumeNumber = $recoveryVolumeNumber.Matches.Groups[1].Value

$patternBoot = "Volume\s+(\d+).*Boot"
$recoveryBootNumber = ($rawDiskInfo | Select-String -Pattern $patternBoot)
$recoveryBootNumber = $recoveryBootNumber.Matches.Groups[1].Value

$diskpartScriptRemoveRecovery = @"
select disk 0
select volume $recoveryVolumeNumber
delete volume override

select volume $recoveryBootNumber
extend
"@

RemoteExecuteDiskpartScript -diskpartScript $diskpartScriptRemoveRecovery
