param(
    [Parameter(Mandatory = $true)]
    [string]$VHDxPath,
    [Parameter(Mandatory = $false)]
    [string]$MountFolder = $null
)
Set-Location $PSScriptRoot
.("..\AOFLibrary\AOFLibrary.ps1")
$ScriptName = "MountVHDx"
$LogFile = BeginScriptLogging -ScriptName $ScriptName
try {
    $vhdx = Mount-VHD -Path $VHDxPath -NoDriveLetter -Passthru -ErrorAction Stop
    if ($MountFolder) 
    {
        # Create $MountFolder to mount the drive to if it doesn't exist
        if(-not (Test-Path -Path $MountFolder -PathType Container))
        {
            New-Item -Path $MountFolder -ItemType Directory -ErrorAction Stop | Out-Null
        }
        # $MountFolder exists, but it might be a mount point, remove the mount point and recreate the folder if so
        elseif ((Get-Item -Path $MountFolder).Attributes -band [System.IO.FileAttributes]::ReparsePoint) 
        {
            try { fsutil reparsepoint delete $MountFolder 2>$null } catch {}
            Remove-Item -Path $MountFolder -Force
            New-Item -Path $MountFolder -ItemType Directory -ErrorAction Stop | Out-Null
        }
        
        $vhdx | Get-Disk | Get-Partition | Where-Object { ($_ | Get-Volume) -ne $Null } | 
                Add-PartitionAccessPath -AccessPath $MountFolder -ErrorAction Stop
    }    
}
catch {
    HandleScriptExecutionError -Message "Disk mount error: $($_.Exception.Message)" -Log $LogFile
}

Write-ScriptSuccess -Log $LogFile
