modules/Initialize-VHDFromWIM.psm1

Set-StrictMode -Version "Latest"


. "$PSSCriptRoot\..\detail\Assert-RunningAsAdmin.ps1"
. "$PSScriptRoot\..\detail\Invoke-WithResource.ps1"


function Initialize-VHDFromWIM {
    [OutputType([Microsoft.Vhd.PowerShell.VirtualHardDisk])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = "VHDPath")]
        [AllowEmptyString()]
        [string]
            $Path,
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = "VHDObject")]
        [Microsoft.Vhd.PowerShell.VirtualHardDisk]
        [Alias("VHD")]
            $InputObject,
        [Parameter(Mandatory = $true)]
        [string]
            $WIMPath,
        [Parameter(Mandatory = $true)]
        [int]
            $ImageIndex,
        [Parameter(Mandatory = $false)]
        [ValidateSet("GPT", "MBR")]
        [string]
            $PartitionStyle = "GPT",
        [Parameter(Mandatory = $false)]
        [AllowEmptyString()]
        [string]
            $UnattendXMLContents,
        [Parameter(Mandatory = $false)]
        [Switch]
            $CreateRecoveryPartition
    )

    Assert-RunningAsAdmin

    # Any error should make us stop.
    $ErrorActionPreference = "Stop"

    $parameters_to_pass_through = [hashtable]$PSBoundParameters

    if ($PSCmdlet.ParameterSetName -eq "VHDPath") {
        $VHD = Get-VHD -Path $Path
    }
    elseif ($PSCmdlet.ParameterSetName -eq "VHDObject") {
        $VHD = $InputObject
    }
    else {
        throw "Impossible. Unknown parameter set name: $($PSCmdlet.ParameterSetName)."
    }

    $parameters_to_pass_through.Remove("InputObject")
    $parameters_to_pass_through.Remove("Path")

    Invoke-WithResource -InitBlock {
        [Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssignments', '')]
        $mounted_VHD = Mount-DiskImage -ImagePath $VHD.Path
    } -CleanupBlock {
        $mounted_VHD | Dismount-DiskImage | Out-Null
        Remove-Variable -Name "mounted_VHD"
    } -BodyBlock {
        $mounted_VHD_disk = $mounted_VHD | Get-Disk

        # We don't need the disk back so Out-Null it.
        $mounted_VHD_disk | Initialize-DiskFromWIM @parameters_to_pass_through | Out-Null 
    }

    Write-Output $VHD
}