WindowsImageTools.psm1

function cleanupFile
{
    param
    (
        [string[]] $file
    )

    foreach ($target in $file)
    {
        if (Test-Path -Path $target)
        {
            Remove-Item -Path $target -Recurse -Force
        }
    }
}
function Get-FullFilePath
{
    <#
      .Synopsis
      Get Absolute path from relative path
      .DESCRIPTION
      Takes a relative path like .\file.txt and returns the full path.
      The target file does not have to exist, but the parent folder must exist
      .EXAMPLE
      $path = Get-AbsoluteFilePath -Path .\file.txt
      #>

    [CmdletBinding()]
    [OutputType([string])]
    Param
    (
        # Path to file
        [Parameter(Mandatory, HelpMessage = 'Path to file',
            ValueFromPipeline,
            Position = 0)]
        [String]$Path
    )

    if (-not (Test-Path -Path $Path))
    {
        if (Test-Path -Path (Split-Path -Path $Path -Parent ))
        {
            $Parent = Resolve-Path -Path (Split-Path -Path $Path -Parent )
            $Leaf = Split-Path -Path $Path -Leaf

            if ($Parent.path[-1] -eq '\')
            {
                $Path = "$Parent" + "$Leaf"
            }
            else
            {
                $Path = "$Parent" + "\$Leaf"
            }
        }
        else
        {
            throw "Parent [$(Split-Path -Path $Path -Parent)] does not exist"
        }
    }
    else
    {
        $Path = Resolve-Path -Path $Path
    }

    return $Path
}
function Initialize-DiskPartition
{
    <#
    .Synopsis
    Initialize a disk and create partitions
    .DESCRIPTION
    This command will will create partition(s) on a give disk. Supported layours are: BIOS, UEFI, WindowsToGo, Data.
 
    To create a recovery partitions use -RecoveryTools and -RecoveryImage
 
    .EXAMPLE
    Initialize-VDiskPartition -DiskNumber 5 -dynamic -size 30GB -DiskLayout BIOS
    .EXAMPLE
    Initialize-VHDPartition -DiskNumber 4 -dynamic -size 40GB -DiskLayout UEFI -NoRecoveryTools
    .EXAMPLE
    Initialize-VHDPartition -DiskNumber 1 -dynamic -size 40GB -DiskLayout Data -DataFormat ReFS
    .NOTES
    This function is intended as a helper for Intilize-VHDDiskPartition
    #>

    [CmdletBinding(SupportsShouldProcess,
        PositionalBinding = $false,
        ConfirmImpact = 'Medium')]
    Param
    (
        # Disk number, disk must exist
        [Parameter(Position = 0, Mandatory,
            HelpMessage = 'Disk Number based on Get-Disk')]
        [ValidateNotNullorEmpty()]
        [ValidateScript( {
                if (Get-Disk -Number $_)
                {
                    $true
                }
                else
                {
                    Throw "Disk number $_ does not exist."
                }
            })]
        [int]$DiskNumber,

        # Specifies whether to build the image for BIOS (MBR), UEFI (GPT), Data (GPT), or WindowsToGo (MBR).
        # Generation 1 VMs require BIOS (MBR) images and have 2-3 partitions. Generation 2 VMs require
        # UEFI (GPT) images and have 3-4 partitions.
        # Windows To Go images will boot in UEFI or BIOS
        [Parameter(Mandatory)]
        [Alias('Layout')]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('BIOS', 'UEFI', 'WindowsToGo', 'Data')]
        $DiskLayout,

        # Format drive as NTFS or ReFS (Only applies when DiskLayout = Data)
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('NTFS', 'ReFS')]
        $DataFormat = 'ReFS',

        # Output the disk object
        [switch]$Passthru,

        # Skip Creation of the Recovery Environment Tools Partition.
        [switch]$NoRecoveryTools,

        # System (boot loader) Partition Size
        [ValidateScript({$_ -ge 100mb})]
        [int]$SystemSize = 260MB,

        # MS Reserved Partition Size
        [ValidateScript({$_ -ge 16mb})]
        [int]$ReservedSize = 128MB,

        # Recovery Tools Partition Size
        [ValidateScript({$_ -ge 200mb})]
        [int]$RecoverySize = 905MB,

        # Force the overwrite of existing files
        [switch]$force
    )
    Begin
    {


        if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] Create [$DiskLayout] partition structure on Disk [$DiskNumber]",
                "Replace existing Partitions on disk [$DiskNumber] ? ",
                'Overwrite WARNING!'))
        {
            if (-not (Get-Disk -Number $DiskNumber | Get-Partition -ErrorAction SilentlyContinue) -Or
                $force -Or
                ((Get-Disk -Number $DiskNumber | Get-Partition -ErrorAction SilentlyContinue) -and $pscmdlet.ShouldContinue("Target Disk [$DiskNumber] has existing partitions! Any existing data will be lost! (suppress with -force)", 'Warning')))
            {
                #region Validate input

                switch ($DiskLayout)
                {
                    'BIOS'
                    {
                        $PartitionStyle = 'MBR'
                        $System = $SystemSize
                        $MsReserved = 0
                        $Recovery = $RecoverySize
                    }
                    'UEFI'
                    {
                        $PartitionStyle = 'GPT'
                        $System = $SystemSize
                        $MsReserved = $ReservedSize
                        $Recovery = $RecoverySize
                    }
                    'Data'
                    {
                        $PartitionStyle = 'GPT'
                        $System = 0
                        $MsReserved = $ReservedSize
                        $Recovery = 0
                    }
                    'WindowsToGo'
                    {
                        $PartitionStyle = 'MBR'
                        $System = $SystemSize
                        $MsReserved = 0
                        $Recovery = 0
                    }
                }
                if ($NoRecoveryTools)
                {
                    $Recovery = 0
                }
                #endregion

                #region create partitions
                try
                {
                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$disknumber] : Clearing disk"
                    Clear-disk -Number $disknumber -RemoveData -RemoveOEM -Confirm:$false -ErrorAction SilentlyContinue
                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$disknumber] : Initializing disk [$disknumber] as [$PartitionStyle]"
                    $null = Initialize-Disk -Number $disknumber -PartitionStyle $PartitionStyle -ErrorAction SilentlyContinue

                    $InitialPartition = Get-Disk -Number $disknumber -ErrorAction Stop |
                    Get-Partition -ErrorAction SilentlyContinue
                    if ($InitialPartition)
                    {
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$disknumber] : Clearing disk to start all over"
                        $InitialPartition | Remove-Partition -Confirm:$false -ErrorAction SilentlyContinue
                    }

                    if ($System)
                    {
                        # Create the system partition. Create a data partition so we can format it, then change to ESP
                        $NewPartitionParam = @{
                            DiskNumber = $diskNumber
                            Size       = $System
                        }
                        switch ($PartitionStyle)
                        {
                            GPT { $NewPartitionParam.add('GptType', '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}') }
                            MBR { $NewPartitionParam.add('IsActive', $true) }
                        }
                        Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : System : Creating partition of [$SysSize] bytes"
                        $systemPartition = New-Partition @NewPartitionParam

                        $FileSystem = 'FAT32'
                        if ($DiskLayout -eq 'Bios')
                        {
                            $FileSystem = 'NTFS'
                        }
                        Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : System : Formatting [$FileSystem]"
                        $null = Format-Volume -Partition $systemPartition -NewFileSystemLabel 'System' -FileSystem $FileSystem -Force -Confirm:$false

                        if ($DiskLayout -eq 'UEFI')
                        {
                            Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : System : Setting system partition as ESP"
                            $systemPartition | Set-Partition -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}'
                        }
                    }

                    if ($MsReserved)
                    {
                        $NewPartitionParam = @{
                            DiskNumber = $disknumber
                            Size       = $MsReserved
                            GptType    = '{e3c9e316-0b5c-4db8-817d-f92df00215ae}'
                        }
                        Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : MSR : Creating partition of [$MsReserved] bytes"
                        $null = New-Partition @NewPartitionParam

                    }

                    #region Create the Primay partition
                    # Refresh $disk to update free space
                    $disk = Get-Disk -Number $disknumber | Get-Disk

                    $NewPartitionParam = @{
                        DiskNumber = $disknumber
                        Size       = $disk.LargestFreeExtent - $Recovery
                    }
                    if ($PartitionStyle -eq 'GPT') { $NewPartitionParam.add('GptType', '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}') }
                    Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : Primary : Creating partition of [$($disk.LargestFreeExtent - $Recovery)] bytes"
                    Write-Verbose ($NewPartitionParam | out-string)
                    $windowsPartition = New-Partition @NewPartitionParam

                    $FileSystem = 'NTFS'
                    $Label = 'Windows'
                    if ($DiskLayout -eq 'Data')
                    {
                        $FileSystem = $DataFormat
                        $Label = 'Data'
                    }
                    Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : Primary : Formatting volume [$FileSystem]"
                    $null = Format-Volume -Partition $windowsPartition -NewFileSystemLabel $Label -FileSystem $FileSystem -Force -Confirm:$false
                    #endregion Primay Partiton

                    if ($Recovery)
                    {
                        Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : Recovery Tools : Creating partition using remaing free space"
                        $NewPartitionParam = @{
                            DiskNumber = $disknumber
                            Size       = $Recovery
                        }
                        if ($PartitionStyle -eq 'GPT') { $NewPartitionParam.add('GptType', '{de94bba4-06d1-4d40-a16a-bfd50179d6ac}') }
                        $recoveryImagePartition = New-Partition @NewPartitionParam
                        Write-Verbose "[$($MyInvocation.MyCommand)] [$disknumber] : Recovery Tools : Formatting volume NTFS"
                        $null = Format-Volume -Partition $recoveryImagePartition -NewFileSystemLabel 'Recovery Tools' -FileSystem NTFS -Force -Confirm:$false
                        #run diskpart to set partition to hidden and prevent deletion
                        #the here string must be left justified
                        if ($PartitionStyle -eq 'GPT')
                        {
                            $null = @"
select disk $($diskNumber)
select partition $($recoveryImagePartition.partitionNumber)
gpt attributes=0x8000000000000001
exit
"@
 |
                            diskpart.exe
                        }
                        else
                        {
                          $null = @"
select disk $($diskNumber)
select partition $($recoveryImagePartition.partitionNumber)
set id=27
exit
"@
 |
                            diskpart.exe
                        }
                    }

                }
                catch
                {
                    Write-Error -Message "[$($MyInvocation.MyCommand)] [$disknumber] : Creating Partitions"
                    throw $_.Exception.Message
                }
                #endregion create partitions

                if ($Passthru)
                {
                    #write the new disk object to the pipeline
                    Get-Disk -Number $DiskNumber
                }
            }
            else
            {
                Throw "[$($MyInvocation.MyCommand)] Aborted by user"
            }
        }
    }
}
function Initialize-VHDPartition
{
    <#
    .Synopsis
    Create VHD(X) with partitions needed to be bootable
    .DESCRIPTION
    This command will create a VHD or VHDX file. Supported layours are: BIOS, UEFI, Data or WindowsToGo.
 
    To create a recovery partitions use -RecoveryTools and -RecoveryImage
 
    .EXAMPLE
    Initialize-VHDPartition d:\disks\disk001.vhdx -dynamic -size 30GB -DiskLayout BIOS
    .EXAMPLE
    Initialize-VHDPartition d:\disks\disk001.vhdx -dynamic -size 40GB -DiskLayout UEFI -RecoveryTools
    .NOTES
    General notes
    #>

    [CmdletBinding(SupportsShouldProcess,
        PositionalBinding = $false,
        ConfirmImpact = 'Medium')]
    Param
    (
        # Path to the new VHDX file (Must end in .vhd, or .vhdx)
        [Parameter(Position = 0, Mandatory,
            HelpMessage = 'Enter the path for the new VHD/VHDX file')]
        [ValidateNotNullorEmpty()]
        [ValidatePattern(".\.vhdx?$")]
        [ValidateScript( {
                if (Get-FullFilePath -Path $_ |
                    Split-Path |
                    Resolve-Path )
                {
                    $true
                }
                else
                {
                    Throw "Parent folder for $_ does not exist."
                }
            })]
        [string]$Path,

        # Size in Bytes (Default 80B)
        [ValidateRange(25GB, 64TB)]
        [uint64]$Size = 80GB,

        # System (boot loader) Partition Size (Default : 260MB)
        [int]$SystemSize,

        # MS Reserved Partition Size (Default : 128MB)
        [int]$ReservedSize,

        # Recovery Tools Partition Size (Default : 905MB)
        [int]$RecoverySize,

        # Create Dynamic disk
        [switch]$Dynamic,

        # Specifies whether to build the image for BIOS (MBR), UEFI (GPT), Data (GPT), or WindowsToGo (MBR).
        # Generation 1 VMs require BIOS (MBR) images and have one partition. Generation 2 VMs require
        # UEFI (GPT) images and have 3-5 partitions.
        # Windows To Go images will boot in UEFI or BIOS
        [Parameter(Mandatory)]
        [Alias('Layout')]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('BIOS', 'UEFI', 'WindowsToGo', 'Data')]
        $DiskLayout,

        # Format drive as NTFS or ReFS (Only applies when DiskLayout = Data)
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('NTFS', 'ReFS')]
        $DataFormat = 'ReFS',

        # Output the disk image object
        [switch]$Passthru,

        # Create the Recovery Environment Tools Partition. Only valid on UEFI layout
        [switch]$NoRecoveryTools,

        # Force the overwrite of existing files
        [switch]$force
    )
    Begin
    {


        if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] Create partition structure for Bootable vhd(x) on [$Path]",
                "Replace existing file [$Path] ? ",
                'Overwrite WARNING!'))
        {
            if ((-not (Test-Path $Path)) -Or
                $force -Or
                ((Test-Path $Path) -and $pscmdlet.ShouldContinue("TargetFile [$Path] exists! Any existin data will be lost!", 'Warning')))
            {

                $ParametersToPass = @{ }
                foreach ($key in ('Whatif', 'Verbose', 'Debug'))
                {
                    if ($PSBoundParameters.ContainsKey($key))
                    {
                        $ParametersToPass[$key] = $PSBoundParameters[$key]
                    }
                }

                #region Validate input

                $VHDFormat = ([IO.FileInfo]$Path).Extension.split('.')[-1]

                if (($DiskLayout -eq 'UEFI') -and ($VHDFormat -eq 'VHD'))
                {
                    throw 'UEFI disks must be in VHDX format. Please change the path to end in VHDX'
                }

                # Enforce max VHD size.
                if ('VHD' -ilike $VHDFormat)
                {
                    if ($Size -gt 2040GB)
                    {
                        Write-Warning -Message 'For the VHD file format, the maximum file size is ~2040GB. Reseting size to 2040GB.'
                        $Size = 2040GB
                    }
                }

                $fileName = Split-Path -Leaf -Path $Path

                # make paths absolute
                $Path = $Path | Get-FullFilePath
                #endregion

                # if we get this far it's ok to delete existing files. Save the ACL for the new file
                $Acl = $null
                if (Test-Path -Path $Path)
                {
                    $Acl = Get-Acl -Path $Path
                    Remove-Item -Path $Path
                }
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$fileName] : Creating"

                #region Create VHD
                Try
                {
                    $vhdParams = @{
                        VHDFormat = $VHDFormat
                        Path      = $Path
                        SizeBytes = $Size
                    }

                    If ($Dynamic)
                    {
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$fileName] : Params for [WIM2VHD.VirtualHardDisk]::CreateSparseDisk()"
                        Write-Verbose -Message ($vhdParams | Out-String)
                        $null = [WIM2VHD.VirtualHardDisk]::CreateSparseDisk(
                            $VHDFormat,
                            $Path,
                            $Size,
                            $true
                        )
                    }
                    else
                    {
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$fileName] : Params for [WIM2VHD.VirtualHardDisk]::CreateFixedDisk()"
                        Write-Verbose -Message ($vhdParams | Out-String)
                        Write-Warning -Message 'Creating a Fixed Disk May take a long time!'
                        $null = [WIM2VHD.VirtualHardDisk]::CreateFixedDisk(
                            $VHDFormat,
                            $Path,
                            $Size,
                            $true
                        )

                    }
                }
                catch
                {
                    Throw "Failed to create $Path. $($_.Exception.Message)"
                }

                #endregion

                if (Test-Path -Path $Path)
                {
                    if ($Acl)
                    {
                        Set-Acl -Path $Path -AclObject $Acl
                    }
                    #region Mount Image
                    try
                    {
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$fileName] : Mounting disk image"
                        $disk = Mount-DiskImage -ImagePath $Path -PassThru |
                        Get-DiskImage |
                        Get-Disk
                    }
                    catch
                    {
                        throw $_.Exception.Message
                    }
                    #endregion
                }
                else
                {
                    Throw "Failed to create vhd"
                }

                #region Create partitions
                try
                {
                    $InitializeDiskParam = @{
                        DiskNumber = $disk.Number
                        DiskLayout = $DiskLayout
                        force      = $force
                    }
                    if ($DataFormat) { $InitializeDiskParam.add('DataFormat', $DataFormat) }
                    if ($NoRecoveryTools) { $InitializeDiskParam.add('NoRecoveryTools', $NoRecoveryTools) }
                    if ($SystemSize) { $InitializeDiskParam.add('SystemSize', $SystemSize) }
                    if ($ReservedSize) { $InitializeDiskParam.add('ReservedSize', $ReservedSize) }
                    if ($RecoverySize) { $InitializeDiskParam.add('RecoverySize', $RecoverySize) }

                    $null = Initialize-DiskPartition @ParametersToPass @InitializeDiskParam
                    #endregion
                }

                catch
                {
                    Write-Error -Message "[$($MyInvocation.MyCommand)] [$fileName] : Creating Partitions"
                    throw $_.Exception.Message
                }
                #region Dismount
                finally
                {
                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$fileName] : Dismounting disk image"
                    $null = Dismount-DiskImage -ImagePath $Path
                    [System.GC]::Collect()
                }
                #endregion
                if ($Passthru)
                {
                    #write the new disk object to the pipeline
                    Get-DiskImage -ImagePath $Path
                }
            }
        }
    }
}
function MountVHDandRunBlock
{
    param
    (
        [string]$vhd,
        [scriptblock]$block,
        [switch]$ReadOnly
    )

    # This function mounts a VHD, runs a script block and unmounts the VHD.
    # Drive letter of the mounted VHD is stored in $driveLetter - can be used by script blocks
    if ($ReadOnly)
    {
        $virtualDisk = Mount-VHD -Path $vhd -ReadOnly -Passthru
    }
    else
    {
        $virtualDisk = Mount-VHD -Path $vhd -Passthru
    }
    # Workarround for new drive letters in script modules
    $null = Get-PSDrive
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
    $driveLetter = ($virtualDisk |
            Get-Disk |
            Get-Partition |
            Get-Volume).DriveLetter
    & $block

    Dismount-VHD -Path $vhd

    # Wait 2 seconds for activity to clean up
    Start-Sleep -Seconds 2
}
function New-TemporaryDirectory
{
    <#
      .Synopsis
      Create a new Temporary Directory
      .DESCRIPTION
      Creates a new Directory in the $env:temp and returns the System.IO.DirectoryInfo (dir)
      .EXAMPLE
      $TempDirPath = NewTemporaryDirectory
      #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([System.IO.DirectoryInfo])]
    Param
    (
    )

    #return [System.IO.Directory]::CreateDirectory((Join-Path $env:Temp -Ch ([System.IO.Path]::GetRandomFileName().split('.')[0])))

    Begin
    {
        try
        {
            if ($PSCmdlet.ShouldProcess($env:temp))
            {
                $tempDirPath = [System.IO.Directory]::CreateDirectory((Join-Path -Path $env:temp -ChildPath ([System.IO.Path]::GetRandomFileName().split('.')[0])))
            }
        }
        catch
        {
            $errorRecord = [System.Management.Automation.ErrorRecord]::new($_.Exception, 'NewTemporaryDirectoryWriteError', 'WriteError', $env:temp)
            Write-Error -ErrorRecord $errorRecord
            return
        }

        if ($tempDirPath)
        {
            Get-Item -Path $env:temp\$tempDirPath
        }
    }
}
function RunExecutable
{
    <#
      .SYNOPSIS
      Runs an external executable file, and validates the error level.
 
      .PARAMETER Executable
      The path to the executable to run and monitor.
 
      .PARAMETER Arguments
      An array of arguments to pass to the executable when it's executed.
 
      .PARAMETER SuccessfulErrorCode
      The error code that means the executable ran successfully.
      The default value is 0.
      #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory, HelpMessage = 'Path to Executable')]
        [string]
        [ValidateNotNullOrEmpty()]
        $Executable,

        [Parameter(Mandatory, HelpMessage = 'aray of arguments to pass to executable')]
        [string[]]
        [ValidateNotNullOrEmpty()]
        $Arguments,

        [Parameter()]
        [int]
        $SuccessfulErrorCode = 0

    )

    $exeName = Split-Path -Path $Executable -Leaf
    Write-Verbose -Message "[$($MyInvocation.MyCommand)] : Running [$Executable] [$Arguments]"
    $Params = @{
        'FilePath'               = $Executable
        'ArgumentList'           = $Arguments
        'NoNewWindow'            = $true
        'Wait'                   = $true
        'RedirectStandardOutput' = "$($env:temp)\$($exeName)-StandardOutput.txt"
        'RedirectStandardError'  = "$($env:temp)\$($exeName)-StandardError.txt"
        'PassThru'               = $true
    }

    Write-Verbose -Message ($Params | Out-String)
    $ret = Start-Process @Params -ErrorAction SilentlyContinue

    Write-Verbose -Message "[$($MyInvocation.MyCommand)] : Return code was [$($ret.ExitCode)]"

    if ($ret.ExitCode -ne $SuccessfulErrorCode)
    {
        throw "$Executable failed with code $($ret.ExitCode)!"
    }
}
function Set-DiskPartition
{
    <#
    .Synopsis
    Sets the content of a Disk using a source WIM or ISO
    .DESCRIPTION
    This command will copy the content of the SourcePath ISO or WIM and populate the
    partitions found on the disk. You must supply the path to a valid WIM/ISO. You
    should also include the index number for the Windows Edition to install. If the
    recovery partitions are present the source WIM will be copied to the recovery
    partition. Optionally, you can also specify an XML file to be inserted into the
    OS partition as unattend.xml, any Drivers, WindowsUpdate (MSU) or Optional Features
    you want installed. And any additional files to add.
    CAUTION: This command will replace the content partitions.
    .EXAMPLE
    PS C:\> Set-VHDPartition -DiskNumber 0 -SourcePath D:\wim\Win2012R2-Install.wim -Index 1
    .EXAMPLE
    PS C:\> Set-VHDPartition -DiskNumber 0 -SourcePath D:\wim\Win2012R2-Install.wim -Index 1 -Confirm:$false -force -Verbose
    #>

    [CmdletBinding(SupportsShouldProcess = $true,
        PositionalBinding = $true,
        ConfirmImpact = 'Medium')]
    Param
    (
        # Disk number, disk must exist
        [Parameter(Position = 0, Mandatory,
            HelpMessage = 'Disk Number based on Get-Disk')]
        [ValidateNotNullorEmpty()]
        [ValidateScript( {
                if (Get-Disk -Number $_)
                {
                    $true
                }
                else
                {
                    Throw "Disk number $_ does not exist."
                }
            })]
        [int]$DiskNumber,

        # Path to WIM or ISO used to populate VHDX
        [parameter(Position = 1, Mandatory = $true,
            HelpMessage = 'Enter the path to the WIM/ISO file')]
        [ValidateScript( {
                Test-Path -Path (Get-FullFilePath -Path $_ )
            })]
        [string]$SourcePath,

        # Index of image inside of WIM (Default 1)
        [int]$Index = 1,

        # Path to file to copy inside of VHD(X) as C:\unattent.xml
        [ValidateScript( {
                if ($_)
                {
                    Test-Path -Path $_
                }
                else
                {
                    $true
                }
            })]
        [string]$Unattend,

        # Native Boot does not have the boot code on the disk. Only usefull for VHD(X).
        [switch]$NativeBoot,

        # Add payload for all removed features
        [switch]$AddPayloadForRemovedFeature,

        # Feature to turn on (in DISM format)
        [ValidateNotNullOrEmpty()]
        [string[]]$Feature,

        # Feature to remove (in DISM format)
        [ValidateNotNullOrEmpty()]
        [string[]]$RemoveFeature,

        # Feature Source path. If not provided, all ISO and WIM images in $sourcePath searched
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                (Test-Path -Path $(Resolve-Path $_) -or ($_ -eq 'NONE') )
            })]
        [string]$FeatureSource,

        # Feature Source index. If the source is a .wim provide an index Default =1
        [int]$FeatureSourceIndex = 1,

        # Path to drivers to inject
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                foreach ($Path in $_)
                {
                    Test-Path -Path $(Resolve-Path $Path)
                }
            })]
        [string[]]$Driver,

        # Path of packages to install via DSIM
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                foreach ($Path in $_)
                {
                    Test-Path -Path $(Resolve-Path $Path)
                }
            })]
        [string[]]$Package,

        # Files/Folders to copy to root of Winodws Drive (to place files in directories mimic the direcotry structure off of C:\)
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                foreach ($Path in $_)
                {
                    Test-Path -Path $(Resolve-Path $Path)
                }
            })]
        [string[]]$filesToInject,

        # Bypass the warning and about lost data
        [switch]$Force
    )


    Process
    {
        $SourcePath = $SourcePath | Get-FullFilePath

        if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] : Overwrite partitions inside [$Path] with content of [$SourcePath]",
                "Overwrite partitions inside [$Path] with contentce of [$SourcePath]? ",
                'Overwrite WARNING!'))
        {
            if ($Force -Or $pscmdlet.ShouldContinue('Are you sure? Any existin data will be lost!', 'Warning'))
            {
                $ParametersToPass = @{ }
                foreach ($key in ('Whatif', 'Verbose', 'Debug'))
                {
                    if ($PSBoundParameters.ContainsKey($key))
                    {
                        $ParametersToPass[$key] = $PSBoundParameters[$key]
                    }
                }
                #region ISO detection
                # If we're using an ISO, mount it and get the path to the WIM file.
                if (([IO.FileInfo]$SourcePath).Extension -ilike '.ISO')
                {

                    $isoPath = (Resolve-Path $SourcePath).Path

                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] : Opening ISO [$(Split-Path -Path $isoPath -Leaf)]"
                    $openIso = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru
                    # Workarround for new drive letters in script modules
                    $null = Get-PSDrive
                    # Refresh the DiskImage object so we can get the real information about it. I assume this is a bug.
                    $openIso = Get-DiskImage -ImagePath $isoPath
                    $driveLetter = ($openIso | Get-Volume).DriveLetter

                    $SourcePath = "$($driveLetter):\sources\install.wim"

                    # Check to see if there's a WIM file.
                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] : Looking for $($SourcePath)"
                    if (!(Test-Path $SourcePath))
                    {
                        throw 'The specified ISO does not appear to be valid Windows installation media.'
                    }
                }
                #endregion ISO detection

                try
                {
                    #! Workarround for new drive letters in script modules
                    $null = Get-PSDrive

                    #region Assign Drive Letters (disable explorer popup and reset afterwords)
                    $DisableAutoPlayOldValue = (Get-ItemProperty -path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -name DisableAutoplay).DisableAutoplay
                    Set-ItemProperty -Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -Value 1
                    foreach ($partition in (Get-Partition -DiskNumber $DiskNumber |
                            Where-Object -Property DriveLetter -EQ 0x00 |
                            Where-Object -Property Type -NE -Value Reserved))
                    {
                        $partition | Add-PartitionAccessPath -AssignDriveLetter -ErrorAction Stop
                    }
                    #! Workarround for new drive letters in script modules
                    $null = Get-PSDrive
                    Set-ItemProperty -Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -Value $DisableAutoPlayOldValue

                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Partition Table"
                    Write-Verbose -Message (Get-Partition -DiskNumber $DiskNumber |
                        Select-Object -Property PartitionNumber, DriveLetter, Size, Type |
                        Out-String)
                    #endregion

                    #region get partitions
                    $RecoveryToolsPartition = Get-Partition -DiskNumber $DiskNumber |
                    Where-Object -Property Type -EQ -Value Recovery |
                    Select-Object -First 1
                    $WindowsPartition = Get-Partition -DiskNumber $DiskNumber |
                    Where-Object -Property Type -EQ -Value Basic |
                    Select-Object -First 1
                    $SystemPartition = Get-Partition -DiskNumber $DiskNumber |
                    Where-Object -Property Type -EQ -Value System |
                    Select-Object -First 1

                    $DiskLayout = 'UEFI'
                    if (-not ($WindowsPartition -and $SystemPartition))
                    {
                        $WindowsPartition = Get-Partition -DiskNumber $DiskNumber |
                        Where-Object -Property Type -EQ -Value IFS |
                        Sort-Object -Descending -Property Size |
                        Select-Object -First 1
                        $SystemPartition = Get-Partition -DiskNumber $DiskNumber |
                        Where-Object -Property Type -EQ -Value IFS |
                        Sort-Object -Property Size |
                        Select-Object -First 1
                        $DiskLayout = 'BIOS'
                    }

                    if (Get-Partition -DiskNumber $DiskNumber |
                        Where-Object -Property Type -Like -Value 'FAT32*' )
                    {
                        $WindowsPartition = Get-Partition -DiskNumber $DiskNumber |
                        Where-Object -Property Type -EQ -Value IFS |
                        Sort-Object -Descending -Property Size |
                        Select-Object -First 1
                        $SystemPartition = Get-Partition -DiskNumber $DiskNumber |
                        Where-Object -Property Type -Like -Value 'FAT32*' |
                        Sort-Object -Property Size |
                        Select-Object -First 1
                        $DiskLayout = 'WindowsToGo'
                    }
                    #endregion get partitions

                    #region Windows partition
                    if ($WindowsPartition)
                    {
                        $WinDrive = Join-Path -Path "$($WindowsPartition.DriveLetter):" -ChildPath '\'
                        $windir = Join-Path -Path $WinDrive -ChildPath Windows
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] Windows Partition [$($WindowsPartition.partitionNumber)] : Applying image from [$SourcePath] to [$WinDrive] using Index [$Index]"
                        $null = Expand-WindowsImage -ImagePath $SourcePath -Index $Index -ApplyPath $WinDrive -ErrorAction Stop

                        #region Modify the OS with Drivers, Active Features and Packages
                        if ($Driver)
                        {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Adding Windows Drivers to the Image"

                            $Driver | ForEach-Object -Process
                            {
                                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Driver path: [$PSItem]"
                                $Null = Add-WindowsDriver -Path $WinDrive -Recurse -Driver $PSItem
                            }
                        }
                        if ($filesToInject)
                        {
                            # TODO: varify consistancy for folder path IE: dest exists or not.
                            foreach ($filePath in $filesToInject)
                            {
                                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] Windows Partition [$($WindowsPartition.partitionNumber)] : Adding files from $filePath"
                                $recurse = $false
                                if (Test-Path $filePath -PathType Container)
                                {
                                    $recurse = $true
                                }
                                Copy-Item -Path $filePath -Destination $WinDrive -Recurse:$recurse
                            }
                        }


                        if ($Unattend)
                        {
                            try
                            {
                                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] Windows Partition [$($WindowsPartition.partitionNumber)] : Adding Unattend.xml ($Unattend)"
                                Copy-Item $Unattend -Destination "$WinDrive\unattend.xml"
                            }
                            catch
                            {
                                Write-Error -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Error Adding Unattend.xml "
                                throw $_.Exception.Message
                            }
                        }
                        if ($AddPayloadForRemovedFeature)
                        {
                            $Feature = $Feature + (Get-WindowsOptionalFeature -Path $WinDrive | Where-Object -Property state -EQ -Value 'DisabledWithPayloadRemoved' ).FeatureName
                        }

                        If ($Feature)
                        {
                            try
                            {
                                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) : Colecting posible source paths"
                                $FeatureSourcePath = @()
                                $MountFolderList = @()

                                # ISO
                                if ($driveLetter)
                                {
                                    $FeatureSourcePath += Join-Path -Path "$($driveLetter):" -ChildPath 'sources\sxs'
                                }

                                $notWinPE = $true
                                if ((Resolve-Path -Path $env:temp).drive.name -eq 'X')
                                {
                                    $notWinPE = $false
                                    Write-Warning "WinPE does not support Mounting WIM, Feature sources must be present in the image OR -FeatureSource must be a Folder"
                                }
                                if (($FeatureSource) -and ($FeatureSource -ne 'NONE'))
                                {
                                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) : Source Path provided [$FeatureSource]"
                                    if (($FeatureSource |
                                            Resolve-Path |
                                            Get-Item ).PSIsContainer -eq $true )
                                    {
                                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) : Source Path [$FeatureSource] in folder"
                                        $FeatureSourcePath += $FeatureSource
                                    }
                                    elseif ((($FeatureSource |
                                                Resolve-Path |
                                                Get-Item ).extension -like '.wim') -and $notWinPE)
                                    {
                                        #$FeatureSourcePath += Convert-Path $FeatureSource
                                        $MountFolder = [System.IO.Directory]::CreateDirectory((Join-Path -Path $env:temp -ChildPath ([System.IO.Path]::GetRandomFileName().split('.')[0])))
                                        $MountFolderList += $MountFolder.FullName
                                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) : Mounting Source [$FeatureSource] Index [$FeatureSourceIndex]"
                                        $null = Mount-WindowsImage -ImagePath $FeatureSource -Index $FeatureSourceIndex -Path  $MountFolder.FullName -ReadOnly
                                        $FeatureSourcePath += Join-Path -Path $MountFolder.FullName -ChildPath 'Windows\WinSxS'
                                    }
                                    else
                                    {
                                        if ($FeatureSource -ne 'NONE')
                                        {
                                            Write-Warning -Message "$FeatureSource is not a .wim or folder"
                                        }
                                    }
                                }
                                elseif ($notWinPE)
                                {
                                    #NO $FeatureSource

                                    $images = Get-WindowsImage -ImagePath $SourcePath

                                    foreach ($image in $images)
                                    {
                                        $MountFolder = [System.IO.Directory]::CreateDirectory((Join-Path -Path $env:temp -ChildPath ([System.IO.Path]::GetRandomFileName().split('.')[0])))
                                        $MountFolderList += $MountFolder.FullName
                                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) : Mounting Source [$SourcePath] [$($image.ImageIndex)] [$($image.ImageName)] to [$($MountFolder.FullName)] "
                                        $null = Mount-WindowsImage -ImagePath $SourcePath -Index $image.ImageIndex -Path  $MountFolder.FullName -ReadOnly
                                        $FeatureSourcePath += Join-Path -Path $MountFolder.FullName -ChildPath 'Windows\WinSxS'
                                    }
                                } #end if FeatureSource

                                if ($FeatureSourcePath.count -gt 0)
                                {
                                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) [$Feature] to the Image [$WinDrive] : Search Source Path [$FeatureSourcePath]"
                                    $null = Enable-WindowsOptionalFeature -Path $WinDrive -All -FeatureName $Feature -Source $FeatureSourcePath
                                }
                                else
                                {
                                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Installing Windows Feature(s) [$Feature] to the Image [$WinDrive] : No Source Path"
                                    $null = Enable-WindowsOptionalFeature -Path $WinDrive -All -FeatureName $Feature
                                }
                            }
                            catch
                            {
                                Write-Error -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Error Installing Windows Feature "
                                throw $_.Exception.Message
                            }
                            finally
                            {
                                foreach ($MountFolder in $MountFolderList)
                                {
                                    $null = Dismount-WindowsImage -Path $MountFolder -Discard
                                    Remove-Item $MountFolder
                                }
                            }
                        }

                        if ($Package)
                        {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Adding Windows Packages to the Image"

                            $Package | ForEach-Object -Process {
                                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Package path: [$PSItem]"
                                $Null = Add-WindowsPackage -Path $WinDrive -PackagePath $PSItem
                            }
                        }
                        if ($RemoveFeature)
                        {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Removing Windows Features from the Image [$WinDrive]"

                            try
                            {
                                $null = Disable-WindowsOptionalFeature -Path $WinDrive -FeatureName $RemoveFeature @ParametersToPass
                            }
                            catch
                            {
                                Write-Error -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Error Removeing Windows Feature [$RemoveFeature] "
                                throw $_.Exception.Message
                            }
                        }

                        #endregion
                    }
                    else
                    {
                        throw 'Unable to find OS partition'
                    }
                    #endregion

                    #region System partition
                    if ($SystemPartition -and (-not ($NativeBoot)))
                    {
                        $systemDrive = "$($SystemPartition.driveletter):"


                        $bcdBootArgs = @(
                            "$windir", # Path to the \Windows on the Disk
                            "/s $systemDrive", # Specifies the volume letter of the drive to create the \BOOT folder on.
                            '/v'                        # Enabled verbose logging.
                        )

                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Disk Layout [$DiskLayout]"
                        switch ($DiskLayout)
                        {
                            'UEFI'
                            {
                                $bcdBootArgs += '/f UEFI'   # Specifies the firmware type of the target system partition
                            }
                            'BIOS'
                            {
                                $bcdBootArgs += '/f BIOS'   # Specifies the firmware type of the target system partition
                            }

                            'WindowsToGo'
                            {
                                # Create entries for both UEFI and BIOS if possible
                                if (Test-Path -Path "$($windowsDrive)\Windows\boot\EFI\bootmgfw.efi")
                                {
                                    $bcdBootArgs += '/f ALL'
                                }
                            }
                        }
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] System Partition [$($SystemPartition.partitionNumber)] : Running [$windir\System32\bcdboot.exe] -> $bcdBootArgs"
                        RunExecutable -Executable "$windir\System32\bcdboot.exe" -Arguments $bcdBootArgs @ParametersToPass
                    }
                    #endregion

                    #region Recovery Tools
                    if ($RecoveryToolsPartition)
                    {
                        $recoverfolder = Join-Path -Path "$($RecoveryToolsPartition.DriveLetter):" -ChildPath 'Recovery'
                        $WindowsRe = Join-Path -Path "$recoverfolder" -ChildPath 'WindowsRe'
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] Recovery Tools Partition [$($RecoveryToolsPartition.partitionNumber)] : Creating Recovery\WindowsRE folder [$WindowsRe]"
                        $null = mkdir -Path "$($RecoveryToolsPartition.driveletter):\Recovery\WindowsRE" -ErrorAction SilentlyContinue

                        #the winre.wim file is hidden
                        Get-ChildItem -Path "$windir\System32\recovery\winre.wim" -Hidden |
                        Copy-Item -Destination $WindowsRe.FullName

                        #? Windows 10 and server have this defaulted to enabled and to the same location.
                        #Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] Recovery Tools Partition [$($RecoveryToolsPartition.partitionNumber)] : Register Reovery Image "
                        #$null = Start-Process -NoNewWindow -Wait -FilePath "$windir\System32\reagentc.exe" -ArgumentList "/setreimage /path $WindowsRe /target $windir"
                    }
                    #endregion
                }
                catch
                {
                    Write-Error -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Error setting partition content "
                    throw $_.Exception.Message
                }
                finally
                {
                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Removing Drive letters"
                    Get-Partition -DiskNumber $DiskNumber |
                    Where-Object -FilterScript {
                        $_.driveletter
                    } |
                    Where-Object -Property Type -NE -Value 'Basic' |
                    Where-Object -Property Type -NE -Value 'IFS' |
                    ForEach-Object -Process {
                        $dl = "$($_.DriveLetter):"
                        $_ |
                        Remove-PartitionAccessPath -AccessPath $dl
                    }
                    #dismount
                    if ($isoPath -and (Get-DiskImage $isoPath).Attached)
                    {
                        $null = Dismount-DiskImage -ImagePath $isoPath
                    }
                    Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Finished"
                }
            }
            else
            {
                Write-Warning -Message 'Process aborted by user'
            }
        }
    }
}
function Set-VHDPartition {
  <#
    .Synopsis
    Sets the content of a VHD(x/s) using a source WIM or ISO
    .DESCRIPTION
    This command will copy the content of the SourcePath ISO or WIM and populate the
    partitions found in the VHD(x/s) You must supply the path to the VHD(X/s) file and a
    valid WIM/ISO. You should also include the index number for the Windows Edition
    to install. If the recovery partitions are present the source WIM will be copied
    to the recovery partition. Optionally, you can also specify an XML file to be
    inserted into the OS partition as unattend.xml, any Drivers, WindowsUpdate (MSU)
    or Optional Features you want installed. And any additional files to add.
    CAUTION: This command will replace the content partitions.
    .EXAMPLE
    PS C:\> Set-VHDPartition -Path D:\vhd\demo3.vhdx -SourcePath D:\wim\Win2012R2-Install.wim -Index 1
    .EXAMPLE
    PS C:\> Set-VHDPartition -Path D:\vhd\demo3.vhdx -SourcePath D:\wim\Win2012R2-Install.wim -Index 1 -Confirm:$false -force -Verbose
    #>

  [CmdletBinding(SupportsShouldProcess = $true,
    PositionalBinding = $true,
    ConfirmImpact = 'High')]
  Param
  (
    # Path to VHDX
    [parameter(Position = 0, Mandatory = $true,
      HelpMessage = 'Enter the path to the VHDX file',
      ValueFromPipeline = $true,
      ValueFromPipelineByPropertyName = $true)]
    [Alias('FullName', 'pspath', 'ImagePath')]
    [ValidateScript( {
        Test-Path -Path (Get-FullFilePath -Path $_)
      })]
    [string]$Path,

    # Path to WIM or ISO used to populate VHDX
    [parameter(Position = 1, Mandatory = $true,
      HelpMessage = 'Enter the path to the WIM/ISO file')]
    [ValidateScript( {
        Test-Path -Path (Get-FullFilePath -Path $_ )
      })]
    [string]$SourcePath,

    # Index of image inside of WIM (Default 1)
    [int]$Index = 1,

    # Path to file to copy inside of VHD(X/s) as C:\unattent.xml
    [ValidateScript( {
        if ($_) {
          Test-Path -Path $_
        }
        else {
          $true
        }
      })]
    [string]$Unattend,

    # Native Boot does not have the boot code inside the VHD(x/s) it must exist on the physical disk.
    [switch]$NativeBoot,

    # Add payload for all removed features
    [switch]$AddPayloadForRemovedFeature,

    # Feature to turn on (in DISM format)
    [ValidateNotNullOrEmpty()]
    [string[]]$Feature,

    # Feature to remove (in DISM format)
    [ValidateNotNullOrEmpty()]
    [string[]]$RemoveFeature,

    # Feature Source path. If not provided, all ISO and WIM images in $sourcePath searched (unused if run on WinPE)
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
         ($_ -eq 'NONE') -or (Test-Path -Path $(Resolve-Path $_) )
      })]
    [string]$FeatureSource,

    # Feature Source index. If the source is a .wim provide an index Default =1
    [int]$FeatureSourceIndex = 1,

    # Path to drivers to inject
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        foreach ($Path in $_) {
          Test-Path -Path $(Resolve-Path $Path)
        }
      })]
    [string[]]$Driver,

    # Path of packages to install via DSIM
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        foreach ($Path in $_) {
          Test-Path -Path $(Resolve-Path $Path)
        }
      })]
    [string[]]$Package,

    # Files/Folders to copy to root of Winodws Drive (to place files in directories mimic the direcotry structure off of C:\)
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        foreach ($Path in $_) {
          Test-Path -Path $(Resolve-Path $Path)
        }
      })]
    [string[]]$filesToInject,

    # Bypass the warning and about lost data
    [switch]$Force
  )


  Process {
    $Path = $Path | Get-FullFilePath
    $SourcePath = $SourcePath | Get-FullFilePath

    $VhdxFileName = Split-Path -Leaf -Path $Path

    if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] : Overwrite partitions inside [$Path] with content of [$SourcePath]",
        "Overwrite partitions inside [$Path] with contentce of [$SourcePath]? ",
        'Overwrite WARNING!')) {
      if ($Force -Or $pscmdlet.ShouldContinue('Are you sure? Any existin data will be lost!', 'Warning')) {
        $ParametersToPass = @{}
        foreach ($key in ('Whatif', 'Verbose', 'Debug')) {
          if ($PSBoundParameters.ContainsKey($key)) {
            $ParametersToPass[$key] = $PSBoundParameters[$key]
          }
        }


        #region mount the VHDX file
        try {
          Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Mounting disk image [$Path]"
          $disk = Mount-DiskImage -ImagePath $Path -PassThru |
            Get-DiskImage |
            Get-Disk
        }
        catch {
          throw $_.Exception.Message
        }
        #endregion

        try {
          Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Munted as disknumber [$($disk.Number)]"

          $SetDiskParam = @{
            DiskNumber = $disk.Number
            SourcePath = $SourcePath
            Index = $Index
            force = $force
          }
          if ($Unattend) {$SetDiskParam.add('Unattend', $Unattend)}
          if ($NativeBoot) {$SetDiskParam.add('NativeBoot', $NativeBoot)}
          if ($AddPayloadForRemovedFeature) {$SetDiskParam.add('AddPayloadForRemovedFeature', $AddPayloadForRemovedFeature)}
          if ($Feature) {$SetDiskParam.add('Feature', $Feature)}
          if ($RemoveFeature) {$SetDiskParam.add('RemoveFeature', $RemoveFeature)}
          if ($FeatureSource) {$SetDiskParam.add('FeatureSource', $FeatureSource)}
          if ($FeatureSourceIndex) {$SetDiskParam.add('FeatureSourceIndex', $FeatureSourceIndex)}
          if ($Driver) {$SetDiskParam.add('Driver', $Driver)}
          if ($Package) {$SetDiskParam.add('Package', $Package)}
          if ($filesToInject) {$SetDiskParam.add('filesToInject', $filesToInject)}

          Set-DiskPartition @ParametersToPass @SetDiskParam

        }
        catch {
          Write-Error -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Error setting partition content "
          throw $_.Exception.Message
        }
        finally {
          #dismount
          Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Dismounting"
          $null = Dismount-DiskImage -ImagePath $Path
          if ($isoPath -and (Get-DiskImage $isoPath).Attached) {
            $null = Dismount-DiskImage -ImagePath $isoPath
            [System.GC]::Collect()
          }
          Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Finished"
        }
      }
      else {
        Write-Warning -Message 'Process aborted by user'
      }
    }
    else {
      # Write-Warning 'Process aborted by user'
    }

  }
}
$code      = @"
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.Win32.SafeHandles;
 
namespace WIM2VHD {
 
    /// <summary>
    /// P/Invoke methods and associated enums, flags, and structs.
    /// </summary>
    public class
    NativeMethods {
 
        #region Delegates and Callbacks
        #region WIMGAPI
 
        ///<summary>
        ///User-defined function used with the RegisterMessageCallback or UnregisterMessageCallback function.
        ///</summary>
        ///<param name="MessageId">Specifies the message being sent.</param>
        ///<param name="wParam">Specifies additional message information. The contents of this parameter depend on the value of the
        ///MessageId parameter.</param>
        ///<param name="lParam">Specifies additional message information. The contents of this parameter depend on the value of the
        ///MessageId parameter.</param>
        ///<param name="UserData">Specifies the user-defined value passed to RegisterCallback.</param>
        ///<returns>
        ///To indicate success and to enable other subscribers to process the message return WIM_MSG_SUCCESS.
        ///To prevent other subscribers from receiving the message, return WIM_MSG_DONE.
        ///To cancel an image apply or capture, return WIM_MSG_ABORT_IMAGE when handling the WIM_MSG_PROCESS message.
        ///</returns>
        public delegate uint
        WimMessageCallback(
            uint MessageId,
            IntPtr wParam,
            IntPtr lParam,
            IntPtr UserData
        );
 
        public static void
        RegisterMessageCallback(
            WimFileHandle hWim,
            WimMessageCallback callback) {
 
            uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero);
            int rc = Marshal.GetLastWin32Error();
            if (0 != rc) {
                // Throw an exception if something bad happened on the Win32 end.
                throw
                    new InvalidOperationException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Unable to register message callback."
                ));
            }
        }
 
        public static void
        UnregisterMessageCallback(
            WimFileHandle hWim,
            WimMessageCallback registeredCallback) {
 
            bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback);
            int rc = Marshal.GetLastWin32Error();
            if (!status) {
                throw
                    new InvalidOperationException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Unable to unregister message callback."
                ));
            }
        }
 
        #endregion WIMGAPI
        #endregion Delegates and Callbacks
 
        #region Constants
 
        #region VDiskInterop
 
        /// <summary>
        /// The default depth in a VHD parent chain that this library will search through.
        /// If you want to go more than one disk deep into the parent chain, provide a different value.
        /// </summary>
        public const uint OPEN_VIRTUAL_DISK_RW_DEFAULT_DEPTH = 0x00000001;
 
        public const uint DEFAULT_BLOCK_SIZE = 0x00080000;
        public const uint DISK_SECTOR_SIZE = 0x00000200;
 
        internal const uint ERROR_VIRTDISK_NOT_VIRTUAL_DISK = 0xC03A0015;
        internal const uint ERROR_NOT_FOUND = 0x00000490;
        internal const uint ERROR_IO_PENDING = 0x000003E5;
        internal const uint ERROR_INSUFFICIENT_BUFFER = 0x0000007A;
        internal const uint ERROR_ERROR_DEV_NOT_EXIST = 0x00000037;
        internal const uint ERROR_BAD_COMMAND = 0x00000016;
        internal const uint ERROR_SUCCESS = 0x00000000;
 
        public const uint GENERIC_READ = 0x80000000;
        public const uint GENERIC_WRITE = 0x40000000;
        public const short FILE_ATTRIBUTE_NORMAL = 0x00000080;
        public const uint CREATE_NEW = 0x00000001;
        public const uint CREATE_ALWAYS = 0x00000002;
        public const uint OPEN_EXISTING = 0x00000003;
        public const short INVALID_HANDLE_VALUE = -1;
 
        internal static Guid VirtualStorageTypeVendorUnknown = new Guid("00000000-0000-0000-0000-000000000000");
        internal static Guid VirtualStorageTypeVendorMicrosoft = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B");
 
        #endregion VDiskInterop
 
        #region WIMGAPI
 
        public const uint WIM_FLAG_VERIFY = 0x00000002;
        public const uint WIM_FLAG_INDEX = 0x00000004;
 
        public const uint WM_APP = 0x00008000;
 
        #endregion WIMGAPI
 
        #endregion Constants
 
        #region Enums and Flags
 
        #region VDiskInterop
 
        /// <summary>
        /// Indicates the version of the virtual disk to create.
        /// </summary>
        public enum CreateVirtualDiskVersion : int {
            VersionUnspecified = 0x00000000,
            Version1 = 0x00000001,
            Version2 = 0x00000002
        }
 
        public enum OpenVirtualDiskVersion : int {
            VersionUnspecified = 0x00000000,
            Version1 = 0x00000001,
            Version2 = 0x00000002
        }
 
        /// <summary>
        /// Contains the version of the virtual hard disk (VHD) ATTACH_VIRTUAL_DISK_PARAMETERS structure to use in calls to VHD functions.
        /// </summary>
        public enum AttachVirtualDiskVersion : int {
            VersionUnspecified = 0x00000000,
            Version1 = 0x00000001,
            Version2 = 0x00000002
        }
 
        public enum CompactVirtualDiskVersion : int {
            VersionUnspecified = 0x00000000,
            Version1 = 0x00000001
        }
 
        /// <summary>
        /// Contains the type and provider (vendor) of the virtual storage device.
        /// </summary>
        public enum VirtualStorageDeviceType : int {
            /// <summary>
            /// The storage type is unknown or not valid.
            /// </summary>
            Unknown = 0x00000000,
            /// <summary>
            /// For internal use only. This type is not supported.
            /// </summary>
            ISO = 0x00000001,
            /// <summary>
            /// Virtual Hard Disk device type.
            /// </summary>
            VHD = 0x00000002,
            /// <summary>
            /// Virtual Hard Disk v2 device type.
            /// </summary>
            VHDX = 0x00000003
        }
 
        /// <summary>
        /// Contains virtual hard disk (VHD) open request flags.
        /// </summary>
        [Flags]
        public enum OpenVirtualDiskFlags {
            /// <summary>
            /// No flags. Use system defaults.
            /// </summary>
            None = 0x00000000,
            /// <summary>
            /// Open the VHD file (backing store) without opening any differencing-chain parents. Used to correct broken parent links.
            /// </summary>
            NoParents = 0x00000001,
            /// <summary>
            /// Reserved.
            /// </summary>
            BlankFile = 0x00000002,
            /// <summary>
            /// Reserved.
            /// </summary>
            BootDrive = 0x00000004,
        }
 
        /// <summary>
        /// Contains the bit mask for specifying access rights to a virtual hard disk (VHD).
        /// </summary>
        [Flags]
        public enum VirtualDiskAccessMask {
            /// <summary>
            /// Only Version2 of OpenVirtualDisk API accepts this parameter
            /// </summary>
            None = 0x00000000,
            /// <summary>
            /// Open the virtual disk for read-only attach access. The caller must have READ access to the virtual disk image file.
            /// </summary>
            /// <remarks>
            /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either
            /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail.
            /// </remarks>
            AttachReadOnly = 0x00010000,
            /// <summary>
            /// Open the virtual disk for read-write attaching access. The caller must have (READ | WRITE) access to the virtual disk image file.
            /// </summary>
            /// <remarks>
            /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either
            /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail.
            /// If the virtual disk is part of a differencing chain, the disk for this request cannot be less than the readWriteDepth specified
            /// during the prior open request for that differencing chain.
            /// </remarks>
            AttachReadWrite = 0x00020000,
            /// <summary>
            /// Open the virtual disk to allow detaching of an attached virtual disk. The caller must have
            /// (FILE_READ_ATTRIBUTES | FILE_READ_DATA) access to the virtual disk image file.
            /// </summary>
            Detach = 0x00040000,
            /// <summary>
            /// Information retrieval access to the virtual disk. The caller must have READ access to the virtual disk image file.
            /// </summary>
            GetInfo = 0x00080000,
            /// <summary>
            /// Virtual disk creation access.
            /// </summary>
            Create = 0x00100000,
            /// <summary>
            /// Open the virtual disk to perform offline meta-operations. The caller must have (READ | WRITE) access to the virtual
            /// disk image file, up to readWriteDepth if working with a differencing chain.
            /// </summary>
            /// <remarks>
            /// If the virtual disk is part of a differencing chain, the backing store (host volume) is opened in RW exclusive mode up to readWriteDepth.
            /// </remarks>
            MetaOperations = 0x00200000,
            /// <summary>
            /// Reserved.
            /// </summary>
            Read = 0x000D0000,
            /// <summary>
            /// Allows unrestricted access to the virtual disk. The caller must have unrestricted access rights to the virtual disk image file.
            /// </summary>
            All = 0x003F0000,
            /// <summary>
            /// Reserved.
            /// </summary>
            Writable = 0x00320000
        }
 
        /// <summary>
        /// Contains virtual hard disk (VHD) creation flags.
        /// </summary>
        [Flags]
        public enum CreateVirtualDiskFlags {
            /// <summary>
            /// Contains virtual hard disk (VHD) creation flags.
            /// </summary>
            None = 0x00000000,
            /// <summary>
            /// Pre-allocate all physical space necessary for the size of the virtual disk.
            /// </summary>
            /// <remarks>
            /// The CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION flag is used for the creation of a fixed VHD.
            /// </remarks>
            FullPhysicalAllocation = 0x00000001
        }
 
        /// <summary>
        /// Contains virtual disk attach request flags.
        /// </summary>
        [Flags]
        public enum AttachVirtualDiskFlags {
            /// <summary>
            /// No flags. Use system defaults.
            /// </summary>
            None = 0x00000000,
            /// <summary>
            /// Attach the virtual disk as read-only.
            /// </summary>
            ReadOnly = 0x00000001,
            /// <summary>
            /// No drive letters are assigned to the disk's volumes.
            /// </summary>
            /// <remarks>Oddly enough, this doesn't apply to NTFS mount points.</remarks>
            NoDriveLetter = 0x00000002,
            /// <summary>
            /// Will decouple the virtual disk lifetime from that of the VirtualDiskHandle.
            /// The virtual disk will be attached until the Detach() function is called, even if all open handles to the virtual disk are closed.
            /// </summary>
            PermanentLifetime = 0x00000004,
            /// <summary>
            /// Reserved.
            /// </summary>
            NoLocalHost = 0x00000008
        }
 
        [Flags]
        public enum DetachVirtualDiskFlag {
            None = 0x00000000
        }
 
        [Flags]
        public enum CompactVirtualDiskFlags {
            None = 0x00000000,
            NoZeroScan = 0x00000001,
            NoBlockMoves = 0x00000002
        }
 
        #endregion VDiskInterop
 
        #region WIMGAPI
 
        [FlagsAttribute]
        internal enum
        WimCreateFileDesiredAccess
            : uint {
            WimQuery = 0x00000000,
            WimGenericRead = 0x80000000
        }
 
        /// <summary>
        /// Specifies how the file is to be treated and what features are to be used.
        /// </summary>
        [FlagsAttribute]
        internal enum
        WimApplyFlags
            : uint {
            /// <summary>
            /// No flags.
            /// </summary>
            WimApplyFlagsNone = 0x00000000,
            /// <summary>
            /// Reserved.
            /// </summary>
            WimApplyFlagsReserved = 0x00000001,
            /// <summary>
            /// Verifies that files match original data.
            /// </summary>
            WimApplyFlagsVerify = 0x00000002,
            /// <summary>
            /// Specifies that the image is to be sequentially read for caching or performance purposes.
            /// </summary>
            WimApplyFlagsIndex = 0x00000004,
            /// <summary>
            /// Applies the image without physically creating directories or files. Useful for obtaining a list of files and directories in the image.
            /// </summary>
            WimApplyFlagsNoApply = 0x00000008,
            /// <summary>
            /// Disables restoring security information for directories.
            /// </summary>
            WimApplyFlagsNoDirAcl = 0x00000010,
            /// <summary>
            /// Disables restoring security information for files
            /// </summary>
            WimApplyFlagsNoFileAcl = 0x00000020,
            /// <summary>
            /// The .wim file is opened in a mode that enables simultaneous reading and writing.
            /// </summary>
            WimApplyFlagsShareWrite = 0x00000040,
            /// <summary>
            /// Sends a WIM_MSG_FILEINFO message during the apply operation.
            /// </summary>
            WimApplyFlagsFileInfo = 0x00000080,
            /// <summary>
            /// Disables automatic path fixups for junctions and symbolic links.
            /// </summary>
            WimApplyFlagsNoRpFix = 0x00000100,
            /// <summary>
            /// Returns a handle that cannot commit changes, regardless of the access level requested at mount time.
            /// </summary>
            WimApplyFlagsMountReadOnly = 0x00000200,
            /// <summary>
            /// Reserved.
            /// </summary>
            WimApplyFlagsMountFast = 0x00000400,
            /// <summary>
            /// Reserved.
            /// </summary>
            WimApplyFlagsMountLegacy = 0x00000800
        }
 
        public enum WimMessage : uint {
            WIM_MSG = WM_APP + 0x1476,
            WIM_MSG_TEXT,
            ///<summary>
            ///Indicates an update in the progress of an image application.
            ///</summary>
            WIM_MSG_PROGRESS,
            ///<summary>
            ///Enables the caller to prevent a file or a directory from being captured or applied.
            ///</summary>
            WIM_MSG_PROCESS,
            ///<summary>
            ///Indicates that volume information is being gathered during an image capture.
            ///</summary>
            WIM_MSG_SCANNING,
            ///<summary>
            ///Indicates the number of files that will be captured or applied.
            ///</summary>
            WIM_MSG_SETRANGE,
            ///<summary>
            ///Indicates the number of files that have been captured or applied.
            ///</summary>
            WIM_MSG_SETPOS,
            ///<summary>
            ///Indicates that a file has been either captured or applied.
            ///</summary>
            WIM_MSG_STEPIT,
            ///<summary>
            ///Enables the caller to prevent a file resource from being compressed during a capture.
            ///</summary>
            WIM_MSG_COMPRESS,
            ///<summary>
            ///Alerts the caller that an error has occurred while capturing or applying an image.
            ///</summary>
            WIM_MSG_ERROR,
            ///<summary>
            ///Enables the caller to align a file resource on a particular alignment boundary.
            ///</summary>
            WIM_MSG_ALIGNMENT,
            WIM_MSG_RETRY,
            ///<summary>
            ///Enables the caller to align a file resource on a particular alignment boundary.
            ///</summary>
            WIM_MSG_SPLIT,
            WIM_MSG_SUCCESS = 0x00000000,
            WIM_MSG_ABORT_IMAGE = 0xFFFFFFFF
        }
 
        internal enum
        WimCreationDisposition
            : uint {
            WimOpenExisting = 0x00000003,
        }
 
        internal enum
        WimActionFlags
            : uint {
            WimIgnored = 0x00000000
        }
 
        internal enum
        WimCompressionType
            : uint {
            WimIgnored = 0x00000000
        }
 
        internal enum
        WimCreationResult
            : uint {
            WimCreatedNew = 0x00000000,
            WimOpenedExisting = 0x00000001
        }
 
        #endregion WIMGAPI
 
        #endregion Enums and Flags
 
        #region Structs
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct CreateVirtualDiskParameters {
            /// <summary>
            /// A CREATE_VIRTUAL_DISK_VERSION enumeration that specifies the version of the CREATE_VIRTUAL_DISK_PARAMETERS structure being passed to or from the virtual hard disk (VHD) functions.
            /// </summary>
            public CreateVirtualDiskVersion Version;
 
            /// <summary>
            /// Unique identifier to assign to the virtual disk object. If this member is set to zero, a unique identifier is created by the system.
            /// </summary>
            public Guid UniqueId;
 
            /// <summary>
            /// The maximum virtual size of the virtual disk object. Must be a multiple of 512.
            /// If a ParentPath is specified, this value must be zero.
            /// If a SourcePath is specified, this value can be zero to specify the size of the source VHD to be used, otherwise the size specified must be greater than or equal to the size of the source disk.
            /// </summary>
            public ulong MaximumSize;
 
            /// <summary>
            /// Internal size of the virtual disk object blocks.
            /// The following are predefined block sizes and their behaviors. For a fixed VHD type, this parameter must be zero.
            /// </summary>
            public uint BlockSizeInBytes;
 
            /// <summary>
            /// Internal size of the virtual disk object sectors. Must be set to 512.
            /// </summary>
            public uint SectorSizeInBytes;
 
            /// <summary>
            /// Optional path to a parent virtual disk object. Associates the new virtual disk with an existing virtual disk.
            /// If this parameter is not NULL, SourcePath must be NULL.
            /// </summary>
            public string ParentPath;
 
            /// <summary>
            /// Optional path to pre-populate the new virtual disk object with block data from an existing disk. This path may refer to a VHD or a physical disk.
            /// If this parameter is not NULL, ParentPath must be NULL.
            /// </summary>
            public string SourcePath;
 
            /// <summary>
            /// Flags for opening the VHD
            /// </summary>
            public OpenVirtualDiskFlags OpenFlags;
 
            /// <summary>
            /// GetInfoOnly flag for V2 handles
            /// </summary>
            public bool GetInfoOnly;
 
            /// <summary>
            /// Virtual Storage Type of the parent disk
            /// </summary>
            public VirtualStorageType ParentVirtualStorageType;
 
            /// <summary>
            /// Virtual Storage Type of the source disk
            /// </summary>
            public VirtualStorageType SourceVirtualStorageType;
 
            /// <summary>
            /// A GUID to use for fallback resiliency over SMB.
            /// </summary>
            public Guid ResiliencyGuid;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct VirtualStorageType {
            public VirtualStorageDeviceType DeviceId;
            public Guid VendorId;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct SecurityDescriptor {
            public byte revision;
            public byte size;
            public short control;
            public IntPtr owner;
            public IntPtr group;
            public IntPtr sacl;
            public IntPtr dacl;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct
        OpenVirtualDiskParameters {
            public OpenVirtualDiskVersion Version;
            public bool GetInfoOnly;
            public Guid ResiliencyGuid;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct VirtualDiskProgress {
            public int OperationStatus;
            public ulong CurrentValue;
            public ulong CompletionValue;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct AttachVirtualDiskParameters {
            public AttachVirtualDiskVersion Version;
            public int Reserved;
        }
 
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct CompactVirtualDiskParameters {
            public CompactVirtualDiskVersion Version;
            public uint Reserved;
        }
 
        #endregion Structs
 
        #region VirtDisk.DLL P/Invoke
 
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        public static extern uint
        CreateVirtualDisk(
            [In, Out] ref VirtualStorageType VirtualStorageType,
            [In] string Path,
            [In] VirtualDiskAccessMask VirtualDiskAccessMask,
            [In, Out] ref SecurityDescriptor SecurityDescriptor,
            [In] CreateVirtualDiskFlags Flags,
            [In] uint ProviderSpecificFlags,
            [In, Out] ref CreateVirtualDiskParameters Parameters,
            [In] IntPtr Overlapped,
            [Out] out SafeFileHandle Handle);
 
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        internal static extern uint
        OpenVirtualDisk(
            [In, Out] ref VirtualStorageType VirtualStorageType,
            [In] string Path,
            [In] VirtualDiskAccessMask VirtualDiskAccessMask,
            [In] OpenVirtualDiskFlags Flags,
            [In, Out] ref OpenVirtualDiskParameters Parameters,
            [Out] out SafeFileHandle Handle);
 
        /// <summary>
        /// GetVirtualDiskOperationProgress API allows getting progress info for the async virtual disk operations (ie. Online Mirror)
        /// </summary>
        /// <param name="VirtualDiskHandle"></param>
        /// <param name="Overlapped"></param>
        /// <param name="Progress"></param>
        /// <returns></returns>
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        internal static extern uint
        GetVirtualDiskOperationProgress(
            [In] SafeFileHandle VirtualDiskHandle,
            [In] IntPtr Overlapped,
            [In, Out] ref VirtualDiskProgress Progress);
 
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        public static extern uint
        AttachVirtualDisk(
            [In] SafeFileHandle VirtualDiskHandle,
            [In, Out] ref SecurityDescriptor SecurityDescriptor,
            [In] AttachVirtualDiskFlags Flags,
            [In] uint ProviderSpecificFlags,
            [In, Out] ref AttachVirtualDiskParameters Parameters,
            [In] IntPtr Overlapped);
 
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        public static extern uint
        DetachVirtualDisk(
            [In] SafeFileHandle VirtualDiskHandle,
            [In] NativeMethods.DetachVirtualDiskFlag Flags,
            [In] uint ProviderSpecificFlags);
 
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        public static extern uint
        CompactVirtualDisk(
            [In] SafeFileHandle VirtualDiskHandle,
            [In] CompactVirtualDiskFlags Flags,
            [In, Out] ref CompactVirtualDiskParameters Parameters,
            [In] IntPtr Overlapped);
 
        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
        public static extern uint
        GetVirtualDiskPhysicalPath(
            [In] SafeFileHandle VirtualDiskHandle,
            [In, Out] ref uint DiskPathSizeInBytes,
            [Out] StringBuilder DiskPath);
 
        #endregion VirtDisk.DLL P/Invoke
 
        #region Win32 P/Invoke
 
        [DllImport("advapi32", SetLastError = true)]
        public static extern bool InitializeSecurityDescriptor(
            [Out] out SecurityDescriptor pSecurityDescriptor,
            [In] uint dwRevision);
 
        /// <summary>
        /// CreateEvent API is used while calling async Online Mirror API
        /// </summary>
        /// <param name="lpEventAttributes"></param>
        /// <param name="bManualReset"></param>
        /// <param name="bInitialState"></param>
        /// <param name="lpName"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        internal static extern IntPtr
        CreateEvent(
            [In, Optional] IntPtr lpEventAttributes,
            [In] bool bManualReset,
            [In] bool bInitialState,
            [In, Optional] string lpName);
 
        #endregion Win32 P/Invoke
 
        #region WIMGAPI P/Invoke
 
        #region SafeHandle wrappers for WimFileHandle and WimImageHandle
 
        public sealed class WimFileHandle : SafeHandle {
 
            public WimFileHandle(
                string wimPath)
                : base(IntPtr.Zero, true) {
 
                if (String.IsNullOrEmpty(wimPath)) {
                    throw new ArgumentNullException("wimPath");
                }
 
                if (!File.Exists(Path.GetFullPath(wimPath))) {
                    throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
                }
 
                NativeMethods.WimCreationResult creationResult;
 
                this.handle = NativeMethods.WimCreateFile(
                    wimPath,
                    NativeMethods.WimCreateFileDesiredAccess.WimGenericRead,
                    NativeMethods.WimCreationDisposition.WimOpenExisting,
                    NativeMethods.WimActionFlags.WimIgnored,
                    NativeMethods.WimCompressionType.WimIgnored,
                    out creationResult
                );
 
                // Check results.
                if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting) {
                    throw new Win32Exception();
                }
 
                if (this.handle == IntPtr.Zero) {
                    throw new Win32Exception();
                }
 
                // Set the temporary path.
                NativeMethods.WimSetTemporaryPath(
                    this,
                    Environment.ExpandEnvironmentVariables("%TEMP%")
                );
            }
 
            protected override bool ReleaseHandle() {
                return NativeMethods.WimCloseHandle(this.handle);
            }
 
            public override bool IsInvalid {
                get { return this.handle == IntPtr.Zero; }
            }
        }
 
        public sealed class WimImageHandle : SafeHandle {
            public WimImageHandle(
                WimFile Container,
                uint ImageIndex)
                : base(IntPtr.Zero, true) {
 
                if (null == Container) {
                    throw new ArgumentNullException("Container");
                }
 
                if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
                    throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
                }
 
                if (ImageIndex > Container.ImageCount) {
                    throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
                }
 
                this.handle = NativeMethods.WimLoadImage(
                    Container.Handle.DangerousGetHandle(),
                    ImageIndex);
            }
 
            protected override bool ReleaseHandle() {
                return NativeMethods.WimCloseHandle(this.handle);
            }
 
            public override bool IsInvalid {
                get { return this.handle == IntPtr.Zero; }
            }
        }
 
        #endregion SafeHandle wrappers for WimFileHandle and WimImageHandle
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")]
        internal static extern IntPtr
        WimCreateFile(
            [In, MarshalAs(UnmanagedType.LPWStr)] string WimPath,
            [In] WimCreateFileDesiredAccess DesiredAccess,
            [In] WimCreationDisposition CreationDisposition,
            [In] WimActionFlags FlagsAndAttributes,
            [In] WimCompressionType CompressionType,
            [Out, Optional] out WimCreationResult CreationResult
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool
        WimCloseHandle(
            [In] IntPtr Handle
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")]
        internal static extern IntPtr
        WimLoadImage(
            [In] IntPtr Handle,
            [In] uint ImageIndex
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")]
        internal static extern uint
        WimGetImageCount(
            [In] WimFileHandle Handle
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMApplyImage")]
        internal static extern bool
        WimApplyImage(
            [In] WimImageHandle Handle,
            [In, Optional, MarshalAs(UnmanagedType.LPWStr)] string Path,
            [In] WimApplyFlags Flags
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool
        WimGetImageInformation(
            [In] SafeHandle Handle,
            [Out] out StringBuilder ImageInfo,
            [Out] out uint SizeOfImageInfo
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool
        WimSetTemporaryPath(
            [In] WimFileHandle Handle,
            [In] string TempPath
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
        internal static extern uint
        WimRegisterMessageCallback(
            [In, Optional] WimFileHandle hWim,
            [In] WimMessageCallback MessageProc,
            [In, Optional] IntPtr ImageInfo
        );
 
        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool
        WimUnregisterMessageCallback(
            [In, Optional] WimFileHandle hWim,
            [In] WimMessageCallback MessageProc
        );
 
 
        #endregion WIMGAPI P/Invoke
    }
 
    #region WIM Interop
 
    public class WimFile {
 
        internal XDocument m_xmlInfo;
        internal List<WimImage> m_imageList;
 
        private static NativeMethods.WimMessageCallback wimMessageCallback;
 
        #region Events
 
        /// <summary>
        /// DefaultImageEvent handler
        /// </summary>
        public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e);
 
        ///<summary>
        ///ProcessFileEvent handler
        ///</summary>
        public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e);
 
        ///<summary>
        ///Enable the caller to prevent a file resource from being compressed during a capture.
        ///</summary>
        public event ProcessFileEventHandler ProcessFileEvent;
 
        ///<summary>
        ///Indicate an update in the progress of an image application.
        ///</summary>
        public event DefaultImageEventHandler ProgressEvent;
 
        ///<summary>
        ///Alert the caller that an error has occurred while capturing or applying an image.
        ///</summary>
        public event DefaultImageEventHandler ErrorEvent;
 
        ///<summary>
        ///Indicate that a file has been either captured or applied.
        ///</summary>
        public event DefaultImageEventHandler StepItEvent;
 
        ///<summary>
        ///Indicate the number of files that will be captured or applied.
        ///</summary>
        public event DefaultImageEventHandler SetRangeEvent;
 
        ///<summary>
        ///Indicate the number of files that have been captured or applied.
        ///</summary>
        public event DefaultImageEventHandler SetPosEvent;
 
        #endregion Events
 
        private
        enum
        ImageEventMessage : uint {
            ///<summary>
            ///Enables the caller to prevent a file or a directory from being captured or applied.
            ///</summary>
            Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS,
            ///<summary>
            ///Notification sent to enable the caller to prevent a file or a directory from being captured or applied.
            ///To prevent a file or a directory from being captured or applied, call WindowsImageContainer.SkipFile().
            ///</summary>
            Process = NativeMethods.WimMessage.WIM_MSG_PROCESS,
            ///<summary>
            ///Enables the caller to prevent a file resource from being compressed during a capture.
            ///</summary>
            Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS,
            ///<summary>
            ///Alerts the caller that an error has occurred while capturing or applying an image.
            ///</summary>
            Error = NativeMethods.WimMessage.WIM_MSG_ERROR,
            ///<summary>
            ///Enables the caller to align a file resource on a particular alignment boundary.
            ///</summary>
            Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT,
            ///<summary>
            ///Enables the caller to align a file resource on a particular alignment boundary.
            ///</summary>
            Split = NativeMethods.WimMessage.WIM_MSG_SPLIT,
            ///<summary>
            ///Indicates that volume information is being gathered during an image capture.
            ///</summary>
            Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING,
            ///<summary>
            ///Indicates the number of files that will be captured or applied.
            ///</summary>
            SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE,
            ///<summary>
            ///Indicates the number of files that have been captured or applied.
            /// </summary>
            SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS,
            ///<summary>
            ///Indicates that a file has been either captured or applied.
            ///</summary>
            StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT,
            ///<summary>
            ///Success.
            ///</summary>
            Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS,
            ///<summary>
            ///Abort.
            ///</summary>
            Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE
        }
 
        ///<summary>
        ///Event callback to the Wimgapi events
        ///</summary>
        private
        uint
        ImageEventMessagePump(
            uint MessageId,
            IntPtr wParam,
            IntPtr lParam,
            IntPtr UserData) {
 
            uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS;
 
            DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData);
 
            switch ((ImageEventMessage)MessageId) {
 
                case ImageEventMessage.Progress:
                    ProgressEvent(this, eventArgs);
                    break;
 
                case ImageEventMessage.Process:
                    if (null != ProcessFileEvent) {
                        string fileToImage = Marshal.PtrToStringUni(wParam);
                        ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam);
                        ProcessFileEvent(this, fileToProcess);
 
                        if (fileToProcess.Abort == true) {
                            status = (uint)ImageEventMessage.Abort;
                        }
                    }
                    break;
 
                case ImageEventMessage.Error:
                    if (null != ErrorEvent) {
                        ErrorEvent(this, eventArgs);
                    }
                    break;
 
                case ImageEventMessage.SetRange:
                    if (null != SetRangeEvent) {
                        SetRangeEvent(this, eventArgs);
                    }
                    break;
 
                case ImageEventMessage.SetPos:
                    if (null != SetPosEvent) {
                        SetPosEvent(this, eventArgs);
                    }
                    break;
 
                case ImageEventMessage.StepIt:
                    if (null != StepItEvent) {
                        StepItEvent(this, eventArgs);
                    }
                    break;
 
                default:
                    break;
            }
            return status;
 
        }
 
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="wimPath">Path to the WIM container.</param>
        public
        WimFile(string wimPath) {
            if (string.IsNullOrEmpty(wimPath)) {
                throw new ArgumentNullException("wimPath");
            }
 
            if (!File.Exists(Path.GetFullPath(wimPath))) {
                throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
            }
 
            Handle = new NativeMethods.WimFileHandle(wimPath);
 
            // Hook up the events before we return.
            //wimMessageCallback = new NativeMethods.WimMessageCallback(ImageEventMessagePump);
            //NativeMethods.RegisterMessageCallback(this.Handle, wimMessageCallback);
        }
 
        /// <summary>
        /// Closes the WIM file.
        /// </summary>
        public void
        Close() {
            foreach (WimImage image in Images) {
                image.Close();
            }
 
            if (null != wimMessageCallback) {
                NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback);
                wimMessageCallback = null;
            }
 
            if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
                Handle.Close();
            }
        }
 
        /// <summary>
        /// Provides a list of WimImage objects, representing the images in the WIM container file.
        /// </summary>
        public List<WimImage>
        Images {
            get {
                if (null == m_imageList) {
 
                    int imageCount = (int)ImageCount;
                    m_imageList = new List<WimImage>(imageCount);
                    for (int i = 0; i < imageCount; i++) {
 
                        // Load up each image so it's ready for us.
                        m_imageList.Add(
                            new WimImage(this, (uint)i + 1));
                    }
                }
 
                return m_imageList;
            }
        }
 
        /// <summary>
        /// Provides a list of names of the images in the specified WIM container file.
        /// </summary>
        public List<string>
        ImageNames {
            get {
                List<string> nameList = new List<string>();
                foreach (WimImage image in Images) {
                    nameList.Add(image.ImageName);
                }
                return nameList;
            }
        }
 
        /// <summary>
        /// Indexer for WIM images inside the WIM container, indexed by the image number.
        /// The list of Images is 0-based, but the WIM container is 1-based, so we automatically compensate for that.
        /// this[1] returns the 0th image in the WIM container.
        /// </summary>
        /// <param name="ImageIndex">The 1-based index of the image to retrieve.</param>
        /// <returns>WinImage object.</returns>
        public WimImage
        this[int ImageIndex] {
            get { return Images[ImageIndex - 1]; }
        }
 
        /// <summary>
        /// Indexer for WIM images inside the WIM container, indexed by the image name.
        /// WIMs created by different processes sometimes contain different information - including the name.
        /// Some images have their name stored in the Name field, some in the Flags field, and some in the EditionID field.
        /// We take all of those into account in while searching the WIM.
        /// </summary>
        /// <param name="ImageName"></param>
        /// <returns></returns>
        public WimImage
        this[string ImageName] {
            get {
                return
                    Images.Where(i => (
                        i.ImageName.ToUpper() == ImageName.ToUpper() ||
                        i.ImageFlags.ToUpper() == ImageName.ToUpper() ))
                    .DefaultIfEmpty(null)
                        .FirstOrDefault<WimImage>();
            }
        }
 
        /// <summary>
        /// Returns the number of images in the WIM container.
        /// </summary>
        internal uint
        ImageCount {
            get { return NativeMethods.WimGetImageCount(Handle); }
        }
 
        /// <summary>
        /// Returns an XDocument representation of the XML metadata for the WIM container and associated images.
        /// </summary>
        internal XDocument
        XmlInfo {
            get {
 
                if (null == m_xmlInfo) {
                    StringBuilder builder;
                    uint bytes;
                    if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
                        throw new Win32Exception();
                    }
 
                    // Ensure the length of the returned bytes to avoid garbage characters at the end.
                    int charCount = (int)bytes / sizeof(char);
                    if (null != builder) {
                        // Get rid of the unicode file marker at the beginning of the XML.
                        builder.Remove(0, 1);
                        builder.EnsureCapacity(charCount - 1);
                        builder.Length = charCount - 1;
 
                        // This isn't likely to change while we have the image open, so cache it.
                        m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
                    } else {
                        m_xmlInfo = null;
                    }
                }
 
                return m_xmlInfo;
            }
        }
 
        public NativeMethods.WimFileHandle Handle {
            get;
            private set;
        }
    }
 
    public class
    WimImage {
 
        internal XDocument m_xmlInfo;
 
        public
        WimImage(
            WimFile Container,
            uint ImageIndex) {
 
            if (null == Container) {
                throw new ArgumentNullException("Container");
            }
 
            if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
                throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
            }
 
            if (ImageIndex > Container.ImageCount) {
                throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
            }
 
            Handle = new NativeMethods.WimImageHandle(Container, ImageIndex);
        }
 
        public enum
        Architectures : uint {
            x86 = 0x0,
            ARM = 0x5,
            IA64 = 0x6,
            AMD64 = 0x9
        }
 
        public void
        Close() {
            if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
                Handle.Close();
            }
        }
 
        public void
        Apply(
            string ApplyToPath) {
 
            if (string.IsNullOrEmpty(ApplyToPath)) {
                throw new ArgumentNullException("ApplyToPath");
            }
 
            ApplyToPath = Path.GetFullPath(ApplyToPath);
 
            if (!Directory.Exists(ApplyToPath)) {
                throw new DirectoryNotFoundException("The WIM cannot be applied because the specified directory was not found.");
            }
 
            if (!NativeMethods.WimApplyImage(
                this.Handle,
                ApplyToPath,
                NativeMethods.WimApplyFlags.WimApplyFlagsNone
            )) {
                throw new Win32Exception();
            }
        }
 
        public NativeMethods.WimImageHandle
        Handle {
            get;
            private set;
        }
 
        internal XDocument
        XmlInfo {
            get {
 
                if (null == m_xmlInfo) {
                    StringBuilder builder;
                    uint bytes;
                    if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
                        throw new Win32Exception();
                    }
 
                    // Ensure the length of the returned bytes to avoid garbage characters at the end.
                    int charCount = (int)bytes / sizeof(char);
                    if (null != builder) {
                        // Get rid of the unicode file marker at the beginning of the XML.
                        builder.Remove(0, 1);
                        builder.EnsureCapacity(charCount - 1);
                        builder.Length = charCount - 1;
 
                        // This isn't likely to change while we have the image open, so cache it.
                        m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
                    } else {
                        m_xmlInfo = null;
                    }
                }
 
                return m_xmlInfo;
            }
        }
 
        public string
        ImageIndex {
            get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; }
        }
 
        public string
        ImageName {
            get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; }
        }
 
        public string
        ImageEditionId {
            get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; }
        }
 
        public string
        ImageFlags {
            get { return XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value; }
        }
 
        public string
        ImageProductType {
            get {
                return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value;
            }
        }
 
        public string
        ImageInstallationType {
            get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; }
        }
 
        public string
        ImageDescription {
            get { return XmlInfo.XPathSelectElement("/IMAGE/DESCRIPTION").Value; }
        }
 
        public ulong
        ImageSize {
            get { return ulong.Parse(XmlInfo.XPathSelectElement("/IMAGE/TOTALBYTES").Value); }
        }
 
        public Architectures
        ImageArchitecture {
            get {
                int arch = -1;
                try {
                    arch = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/ARCH").Value);
                } catch { }
 
                return (Architectures)arch;
            }
        }
 
        public string
        ImageDefaultLanguage {
            get {
                string lang = null;
                try {
                    lang = XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/LANGUAGES/DEFAULT").Value;
                } catch { }
 
                return lang;
            }
        }
 
        public Version
        ImageVersion {
            get {
                int major = 0;
                int minor = 0;
                int build = 0;
                int revision = 0;
 
                try {
                    major = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MAJOR").Value);
                    minor = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MINOR").Value);
                    build = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/BUILD").Value);
                    revision = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/SPBUILD").Value);
                } catch { }
 
                return (new Version(major, minor, build, revision));
            }
        }
 
        public string
        ImageDisplayName {
            get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYNAME").Value; }
        }
 
        public string
        ImageDisplayDescription {
            get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYDESCRIPTION").Value; }
        }
    }
 
    ///<summary>
    ///Describes the file that is being processed for the ProcessFileEvent.
    ///</summary>
    public class
    DefaultImageEventArgs : EventArgs {
        ///<summary>
        ///Default constructor.
        ///</summary>
        public
        DefaultImageEventArgs(
            IntPtr wideParameter,
            IntPtr leftParameter,
            IntPtr userData) {
 
            WideParameter = wideParameter;
            LeftParameter = leftParameter;
            UserData = userData;
        }
 
        ///<summary>
        ///wParam
        ///</summary>
        public IntPtr WideParameter {
            get;
            private set;
        }
 
        ///<summary>
        ///lParam
        ///</summary>
        public IntPtr LeftParameter {
            get;
            private set;
        }
 
        ///<summary>
        ///UserData
        ///</summary>
        public IntPtr UserData {
            get;
            private set;
        }
    }
 
    ///<summary>
    ///Describes the file that is being processed for the ProcessFileEvent.
    ///</summary>
    public class
    ProcessFileEventArgs : EventArgs {
        ///<summary>
        ///Default constructor.
        ///</summary>
        ///<param name="file">Fully qualified path and file name. For example: c:\file.sys.</param>
        ///<param name="skipFileFlag">Default is false - skip file and continue.
        ///Set to true to abort the entire image capture.</param>
        public
        ProcessFileEventArgs(
            string file,
            IntPtr skipFileFlag) {
 
            m_FilePath = file;
            m_SkipFileFlag = skipFileFlag;
        }
 
        ///<summary>
        ///Skip file from being imaged.
        ///</summary>
        public void
        SkipFile() {
            byte[] byteBuffer = {
                    0
            };
            int byteBufferSize = byteBuffer.Length;
            Marshal.Copy(byteBuffer, 0, m_SkipFileFlag, byteBufferSize);
        }
 
        ///<summary>
        ///Fully qualified path and file name.
        ///</summary>
        public string
        FilePath {
            get {
                string stringToReturn = "";
                if (m_FilePath != null) {
                    stringToReturn = m_FilePath;
                }
                return stringToReturn;
            }
        }
 
        ///<summary>
        ///Flag to indicate if the entire image capture should be aborted.
        ///Default is false - skip file and continue. Setting to true will
        ///abort the entire image capture.
        ///</summary>
        public bool Abort {
            set { m_Abort = value; }
            get { return m_Abort; }
        }
 
        private string m_FilePath;
        private bool m_Abort;
        private IntPtr m_SkipFileFlag;
 
    }
 
    #endregion WIM Interop
 
    #region VHD Interop
    // Based on code written by the Hyper-V Test team.
    /// <summary>
    /// The Virtual Hard Disk class provides methods for creating and manipulating Virtual Hard Disk files.
    /// </summary>
    public class
    VirtualHardDisk : IDisposable {
 
        #region Member Variables
 
        private SafeFileHandle m_virtualHardDiskHandle = null;
        private string m_filePath = null;
        private bool m_isDisposed;
        private NativeMethods.VirtualStorageDeviceType m_deviceType = NativeMethods.VirtualStorageDeviceType.Unknown;
 
        #endregion Member Variables
 
        #region IDisposable Members
 
        /// <summary>
        /// Disposal method for Virtual Hard Disk objects.
        /// </summary>
        public void
        Dispose() {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
 
        /// <summary>
        /// Disposal method for Virtual Hard Disk objects.
        /// </summary>
        /// <param name="disposing"></param>
        public void
        Dispose(
            bool disposing) {
            // Check to see if Dispose has already been called.
            if (!this.m_isDisposed) {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing) {
                    // Dispose managed resources.
                    if (this.DiskIndex != 0) {
                        this.Close();
                    }
                }
 
                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.
 
                // Note disposing has been done.
                m_isDisposed = true;
            }
        }
 
        #endregion IDisposable Members
 
        #region Constructor
 
        private VirtualHardDisk(
            SafeFileHandle Handle,
            string Path,
            NativeMethods.VirtualStorageDeviceType DeviceType) {
            if (Handle.IsInvalid || Handle.IsClosed) {
                throw new InvalidOperationException("The handle to the Virtual Hard Disk is invalid.");
            }
 
            m_virtualHardDiskHandle = Handle;
            m_filePath = Path;
            m_deviceType = DeviceType;
        }
 
        #endregion Constructor
 
        #region Gozer the Destructor
        /// <summary>
        /// Destroys a VHD object.
        /// </summary>
        ~VirtualHardDisk() {
            this.Dispose(false);
        }
 
        #endregion Gozer the Destructor
 
        #region Static Methods
 
        #region Sparse Disks
 
        /// <summary>
        /// Abbreviated signature of CreateSparseDisk so it's easier to use from WIM2VHD.
        /// </summary>
        /// <param name="virtualStorageDeviceType">The type of disk to create, VHD or VHDX.</param>
        /// <param name="path">The path of the disk to create.</param>
        /// <param name="size">The maximum size of the disk to create.</param>
        /// <param name="overwrite">Overwrite the VHD if it already exists.</param>
        /// <returns>Virtual Hard Disk object</returns>
        public static VirtualHardDisk
        CreateSparseDisk(
            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
            string path,
            ulong size,
            bool overwrite) {
 
            return CreateSparseDisk(
                path,
                size,
                overwrite,
                null,
                IntPtr.Zero,
                (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                    ? NativeMethods.DEFAULT_BLOCK_SIZE
                    : 0,
                virtualStorageDeviceType,
                NativeMethods.DISK_SECTOR_SIZE);
        }
 
        /// <summary>
        /// Creates a new sparse (dynamically expanding) virtual hard disk (.vhd). Supports both sync and async modes.
        /// The VHD image file uses only as much space on the backing store as needed to store the actual data the VHD currently contains.
        /// </summary>
        /// <param name="path">The path and name of the VHD to create.</param>
        /// <param name="size">The size of the VHD to create in bytes.
        /// When creating this type of VHD, the VHD API does not test for free space on the physical backing store based on the maximum size requested,
        /// therefore it is possible to successfully create a dynamic VHD with a maximum size larger than the available physical disk free space.
        /// The maximum size of a dynamic VHD is 2,040 GB. The minimum size is 3 MB.</param>
        /// <param name="source">Optional path to pre-populate the new virtual disk object with block data from an existing disk
        /// This path may refer to a VHD or a physical disk. Use NULL if you don't want a source.</param>
        /// <param name="overwrite">If the VHD exists, setting this parameter to 'True' will delete it and create a new one.</param>
        /// <param name="overlapped">If not null, the operation runs in async mode</param>
        /// <param name="blockSizeInBytes">Block size for the VHD.</param>
        /// <param name="virtualStorageDeviceType">VHD format version (VHD1 or VHD2)</param>
        /// <param name="sectorSizeInBytes">Sector size for the VHD.</param>
        /// <returns>Returns a SafeFileHandle corresponding to the virtual hard disk that was created.</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when an invalid size is specified</exception>
        /// <exception cref="FileNotFoundException">Thrown when source VHD is not found.</exception>
        /// <exception cref="SecurityException">Thrown when there was an error while creating the default security descriptor.</exception>
        /// <exception cref="Win32Exception">Thrown when an error occurred while creating the VHD.</exception>
        public static VirtualHardDisk
        CreateSparseDisk(
            string path,
            ulong size,
            bool overwrite,
            string source,
            IntPtr overlapped,
            uint blockSizeInBytes,
            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
            uint sectorSizeInBytes) {
 
            // Validate the virtualStorageDeviceType
            if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX) {
 
                throw (
                    new ArgumentOutOfRangeException(
                        "virtualStorageDeviceType",
                        virtualStorageDeviceType,
                        "VirtualStorageDeviceType must be VHD or VHDX."
                ));
            }
 
            // Validate size. It needs to be a multiple of DISK_SECTOR_SIZE (512)...
            if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0) {
 
                throw (
                    new ArgumentOutOfRangeException(
                        "size",
                        size,
                        "The size of the virtual disk must be a multiple of 512."
                ));
            }
 
            if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source))) {
 
                throw (
                    new System.IO.FileNotFoundException(
                        "Unable to find the source file.",
                        source
                ));
            }
 
            if ((overwrite) && (System.IO.File.Exists(path))) {
 
                System.IO.File.Delete(path);
            }
 
            NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters();
 
            // Select the correct version.
            createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                ? NativeMethods.CreateVirtualDiskVersion.Version1
                : NativeMethods.CreateVirtualDiskVersion.Version2;
 
            createParams.UniqueId = Guid.NewGuid();
            createParams.MaximumSize = size;
            createParams.BlockSizeInBytes = blockSizeInBytes;
            createParams.SectorSizeInBytes = sectorSizeInBytes;
            createParams.ParentPath = null;
            createParams.SourcePath = source;
            createParams.OpenFlags = NativeMethods.OpenVirtualDiskFlags.None;
            createParams.GetInfoOnly = false;
            createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType();
            createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType();
 
            //
            // Create and init a security descriptor.
            // Since we're creating an essentially blank SD to use with CreateVirtualDisk
            // the VHD will take on the security values from the parent directory.
            //
 
            NativeMethods.SecurityDescriptor securityDescriptor;
            if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) {
 
                throw (
                    new SecurityException(
                        "Unable to initialize the security descriptor for the virtual disk."
                ));
            }
 
            NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
            virtualStorageType.DeviceId = virtualStorageDeviceType;
            virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
 
            SafeFileHandle vhdHandle;
 
            uint returnCode = NativeMethods.CreateVirtualDisk(
                ref virtualStorageType,
                    path,
                    (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                        ? NativeMethods.VirtualDiskAccessMask.All
                        : NativeMethods.VirtualDiskAccessMask.None,
                ref securityDescriptor,
                    NativeMethods.CreateVirtualDiskFlags.None,
                    0,
                ref createParams,
                    overlapped,
                out vhdHandle);
 
            if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode) {
 
                throw (
                    new Win32Exception(
                        (int)returnCode
                ));
            }
 
            return new VirtualHardDisk(vhdHandle, path, virtualStorageDeviceType);
        }
 
        #endregion Sparse Disks
 
        #region Fixed Disks
 
        /// <summary>
        /// Abbreviated signature of CreateFixedDisk so it's easier to use from WIM2VHD.
        /// </summary>
        /// <param name="virtualStorageDeviceType">The type of disk to create, VHD or VHDX.</param>
        /// <param name="path">The path of the disk to create.</param>
        /// <param name="size">The maximum size of the disk to create.</param>
        /// <param name="overwrite">Overwrite the VHD if it already exists.</param>
        /// <returns>Virtual Hard Disk object</returns>
        public static VirtualHardDisk
        CreateFixedDisk(
            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
            string path,
            ulong size,
            bool overwrite) {
 
            return CreateFixedDisk(
                path,
                size,
                overwrite,
                null,
                IntPtr.Zero,
                0,
                virtualStorageDeviceType,
                NativeMethods.DISK_SECTOR_SIZE);
        }
 
        /// <summary>
        /// Creates a fixed-size Virtual Hard Disk. Supports both sync and async modes. This methods always calls the V2 version of the
        /// CreateVirtualDisk API, and creates VHD2.
        /// </summary>
        /// <param name="path">The path and name of the VHD to create.</param>
        /// <param name="size">The size of the VHD to create in bytes.
        /// The VHD image file is pre-allocated on the backing store for the maximum size requested.
        /// The maximum size of a dynamic VHD is 2,040 GB. The minimum size is 3 MB.</param>
        /// <param name="source">Optional path to pre-populate the new virtual disk object with block data from an existing disk
        /// This path may refer to a VHD or a physical disk. Use NULL if you don't want a source.</param>
        /// <param name="overwrite">If the VHD exists, setting this parameter to 'True' will delete it and create a new one.</param>
        /// <param name="overlapped">If not null, the operation runs in async mode</param>
        /// <param name="blockSizeInBytes">Block size for the VHD.</param>
        /// <param name="virtualStorageDeviceType">Virtual storage device type: VHD1 or VHD2.</param>
        /// <param name="sectorSizeInBytes">Sector size for the VHD.</param>
        /// <returns>Returns a SafeFileHandle corresponding to the virtual hard disk that was created.</returns>
        /// <remarks>Creating a fixed disk can be a time consuming process!</remarks>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when an invalid size or wrong virtual storage device type is specified.</exception>
        /// <exception cref="FileNotFoundException">Thrown when source VHD is not found.</exception>
        /// <exception cref="SecurityException">Thrown when there was an error while creating the default security descriptor.</exception>
        /// <exception cref="Win32Exception">Thrown when an error occurred while creating the VHD.</exception>
        public static VirtualHardDisk
        CreateFixedDisk(
            string path,
            ulong size,
            bool overwrite,
            string source,
            IntPtr overlapped,
            uint blockSizeInBytes,
            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
            uint sectorSizeInBytes) {
 
            // Validate the virtualStorageDeviceType
            if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX) {
 
                throw (
                    new ArgumentOutOfRangeException(
                        "virtualStorageDeviceType",
                        virtualStorageDeviceType,
                        "VirtualStorageDeviceType must be VHD or VHDX."
                ));
            }
 
            // Validate size. It needs to be a multiple of DISK_SECTOR_SIZE (512)...
            if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0) {
 
                throw (
                    new ArgumentOutOfRangeException(
                        "size",
                        size,
                        "The size of the virtual disk must be a multiple of 512."
                ));
            }
 
            if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source))) {
 
                throw (
                    new System.IO.FileNotFoundException(
                        "Unable to find the source file.",
                        source
                ));
            }
 
            if ((overwrite) && (System.IO.File.Exists(path))) {
 
                System.IO.File.Delete(path);
            }
 
            NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters();
 
            // Select the correct version.
            createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                ? NativeMethods.CreateVirtualDiskVersion.Version1
                : NativeMethods.CreateVirtualDiskVersion.Version2;
 
            createParams.UniqueId = Guid.NewGuid();
            createParams.MaximumSize = size;
            createParams.BlockSizeInBytes = blockSizeInBytes;
            createParams.SectorSizeInBytes = sectorSizeInBytes;
            createParams.ParentPath = null;
            createParams.SourcePath = source;
            createParams.OpenFlags = NativeMethods.OpenVirtualDiskFlags.None;
            createParams.GetInfoOnly = false;
            createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType();
            createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType();
 
            //
            // Create and init a security descriptor.
            // Since we're creating an essentially blank SD to use with CreateVirtualDisk
            // the VHD will take on the security values from the parent directory.
            //
 
            NativeMethods.SecurityDescriptor securityDescriptor;
            if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) {
                throw (
                    new SecurityException(
                        "Unable to initialize the security descriptor for the virtual disk."
                ));
            }
 
            NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
            virtualStorageType.DeviceId = virtualStorageDeviceType;
            virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
 
            SafeFileHandle vhdHandle;
 
            uint returnCode = NativeMethods.CreateVirtualDisk(
                ref virtualStorageType,
                    path,
                    (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                        ? NativeMethods.VirtualDiskAccessMask.All
                        : NativeMethods.VirtualDiskAccessMask.None,
                ref securityDescriptor,
                    NativeMethods.CreateVirtualDiskFlags.FullPhysicalAllocation,
                    0,
                ref createParams,
                    overlapped,
                out vhdHandle);
 
            if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode) {
 
                throw (
                    new Win32Exception(
                        (int)returnCode
                ));
            }
 
            return new VirtualHardDisk(vhdHandle, path, virtualStorageDeviceType);
        }
 
        #endregion Fixed Disks
 
        #region Open
 
        /// <summary>
        /// Opens a virtual hard disk (VHD) using the V2 of OpenVirtualDisk Win32 API for use, allowing you to explicitly specify OpenVirtualDiskFlags,
        /// Read/Write depth, and Access Mask information.
        /// </summary>
        /// <param name="path">The path and name of the Virtual Hard Disk file to open.</param>
        /// <param name="accessMask">Contains the bit mask for specifying access rights to a virtual hard disk (VHD). Default is All.</param>
        /// <param name="readWriteDepth">Indicates the number of stores, beginning with the child, of the backing store chain to open as read/write.
        /// The remaining stores in the differencing chain will be opened read-only. This is necessary for merge operations to succeed. Default is 0x1.</param>
        /// <param name="flags">An OpenVirtualDiskFlags object to modify the way the Virtual Hard Disk is opened. Default is Unknown.</param>
        /// <param name="virtualStorageDeviceType">VHD Format Version (VHD1 or VHD2)</param>
        /// <returns>VirtualHardDisk object</returns>
        /// <exception cref="FileNotFoundException">Thrown if the VHD at path is not found.</exception>
        /// <exception cref="Win32Exception">Thrown if an error occurred while opening the VHD.</exception>
        public static VirtualHardDisk
        Open(
            string path,
            NativeMethods.VirtualDiskAccessMask accessMask,
            uint readWriteDepth,
            NativeMethods.OpenVirtualDiskFlags flags,
            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType) {
 
            if (!File.Exists(path)) {
                throw new FileNotFoundException("The specified VHD was not found. Please check your path and try again.", path);
            }
 
            NativeMethods.OpenVirtualDiskParameters openParams = new NativeMethods.OpenVirtualDiskParameters();
 
            // Select the correct version.
            openParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
                ? NativeMethods.OpenVirtualDiskVersion.Version1
                : NativeMethods.OpenVirtualDiskVersion.Version2;
 
            openParams.GetInfoOnly = false;
 
            NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
            virtualStorageType.DeviceId = virtualStorageDeviceType;
 
            virtualStorageType.VendorId = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.Unknown)
                ? virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorUnknown
                : virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
 
            SafeFileHandle vhdHandle;
 
            uint returnCode = NativeMethods.OpenVirtualDisk(
                ref virtualStorageType,
                    path,
                    accessMask,
                    flags,
                ref openParams,
                out vhdHandle);
 
            if (NativeMethods.ERROR_SUCCESS != returnCode) {
                throw new Win32Exception((int)returnCode);
            }
 
            return new VirtualHardDisk(vhdHandle, path, virtualStorageDeviceType);
        }
 
        #endregion Open
 
        #region Other
 
        /// <summary>
        /// Retrieves a collection of drive letters that are currently available on the system.
        /// </summary>
        /// <remarks>Drives A and B are not included in the collection, even if they are available.</remarks>
        /// <returns>A collection of drive letters that are currently available on the system.</returns>
        public static ReadOnlyCollection<Char>
        GetAvailableDriveLetters() {
 
            List<Char> availableDrives = new List<Char>();
            for (int i = (byte)'C'; i <= (byte)'Z'; i++) {
                availableDrives.Add((char)i);
            }
 
            foreach (string drive in System.Environment.GetLogicalDrives()) {
                availableDrives.Remove(drive.ToUpper(CultureInfo.InvariantCulture)[0]);
            }
 
            return new ReadOnlyCollection<char>(availableDrives);
        }
 
        /// <summary>
        /// Gets the first available drive letter on the current system.
        /// </summary>
        /// <remarks>Drives A and B will not be returned, even if they are available.</remarks>
        /// <returns>Char representing the first available drive letter.</returns>
        public static char
        GetFirstAvailableDriveLetter() {
            return GetAvailableDriveLetters()[0];
        }
 
        #endregion Other
 
        #endregion Static Methods
 
        #region AsyncHelpers
 
        /// <summary>
        /// Creates a NativeOverlapped object, initializes its EventHandle property, and pins the object to the memory.
        /// This overlapped objects are useful when executing VHD meta-ops in async mode.
        /// </summary>
        /// <returns>Returns the GCHandle for the pinned overlapped structure</returns>
        public static GCHandle
        CreatePinnedOverlappedObject() {
            NativeOverlapped overlapped = new NativeOverlapped();
            overlapped.EventHandle = NativeMethods.CreateEvent(IntPtr.Zero, true, false, null);
 
            GCHandle handleForOverllapped = GCHandle.Alloc(overlapped, GCHandleType.Pinned);
 
            return handleForOverllapped;
        }
 
        /// <summary>
        /// GetVirtualDiskOperationProgress API allows getting progress info for the async virtual disk operations (ie. Online Mirror)
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="overlapped"></param>
        /// <returns></returns>
        /// <exception cref="Win32Exception">Thrown when an error occurred while mirroring the VHD.</exception>
        public uint
        GetVirtualDiskOperationProgress(
            ref NativeMethods.VirtualDiskProgress progress,
                IntPtr overlapped) {
            uint returnCode = NativeMethods.GetVirtualDiskOperationProgress(
                    this.m_virtualHardDiskHandle,
                    overlapped,
                ref progress);
 
            return returnCode;
        }
 
        #endregion AsyncHelpers
 
        #region Public Methods
 
        /// <summary>
        /// Closes all open handles to the Virtual Hard Disk object.
        /// If the VHD is currently attached, and the PermanentLifetime was not specified, this operation will detach it.
        /// </summary>
        public void
        Close() {
            m_virtualHardDiskHandle.Close();
        }
 
        /// <summary>
        /// Attaches a virtual hard disk (VHD) by locating an appropriate VHD provider to accomplish the attachment.
        /// </summary>
        /// <param name="attachVirtualDiskFlags">
        /// A combination of values from the attachVirtualDiskFlags enumeration which will dictate how the behavior of the VHD once mounted.
        /// </param>
        /// <exception cref="Win32Exception">Thrown when an error occurred while attaching the VHD.</exception>
        /// <exception cref="SecurityException">Thrown when an error occurred while creating the default security descriptor.</exception>
        public void
        Attach(
            NativeMethods.AttachVirtualDiskFlags attachVirtualDiskFlags) {
 
            if (!this.IsAttached) {
 
                // Get the current disk index. We need it later.
                int diskIndex = this.DiskIndex;
 
                NativeMethods.AttachVirtualDiskParameters attachParameters = new NativeMethods.AttachVirtualDiskParameters();
 
                // For attach, the correct version is always Version1 for Win7 and Win8.
                attachParameters.Version = NativeMethods.AttachVirtualDiskVersion.Version1;
                attachParameters.Reserved = 0;
 
                NativeMethods.SecurityDescriptor securityDescriptor;
                if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) {
 
                    throw (new SecurityException("Unable to initialize the security descriptor for the virtual disk."));
                }
 
                uint returnCode = NativeMethods.AttachVirtualDisk(
                         m_virtualHardDiskHandle,
                    ref securityDescriptor,
                         attachVirtualDiskFlags,
                         0,
                    ref attachParameters,
                         IntPtr.Zero);
 
                switch (returnCode) {
 
                    case NativeMethods.ERROR_SUCCESS:
                        break;
 
                    default:
                        throw new Win32Exception((int)returnCode);
                }
 
                // There's apparently a bit of a timing issue here on some systems.
                // If the disk index isn't updated, keep checking once per second for five seconds.
                // If it's not updated after that, it's probably not our fault.
                short attempts = 5;
                while ((attempts-- >= 0) && (diskIndex == this.DiskIndex)) {
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
 
        /// <summary>
        /// Attaches a virtual hard disk (VHD) by locating an appropriate VHD provider to accomplish the attachment.
        /// </summary>
        /// <remarks>
        /// This method attaches the VHD with no flags.
        /// </remarks>
        /// <exception cref="Win32Exception">Thrown when an error occurred while attaching the VHD.</exception>
        /// <exception cref="SecurityException">Thrown when an error occurred while creating the default security descriptor.</exception>
        public void
        Attach() {
 
            this.Attach(NativeMethods.AttachVirtualDiskFlags.None);
        }
 
        /// <summary>
        /// Unsurfaces (detaches) a virtual hard disk (VHD) by locating an appropriate VHD provider to accomplish the operation.
        /// </summary>
        public void
        Detach() {
 
            if (this.IsAttached) {
                uint returnCode = NativeMethods.DetachVirtualDisk(
                    m_virtualHardDiskHandle,
                    NativeMethods.DetachVirtualDiskFlag.None,
                    0);
 
                switch (returnCode) {
 
                    case NativeMethods.ERROR_NOT_FOUND:
                    // There's nothing to do here. The device wasn't found, which means there's a
                    // really good chance that it wasn't attached to begin with.
                    // And, since we were asked to detach it anyway, we can assume that the system
                    // is already in the desired state.
                    case NativeMethods.ERROR_SUCCESS:
                        break;
 
                    default:
                        throw new Win32Exception((int)returnCode);
                }
            }
        }
 
        /// <summary>
        /// Reduces the size of the virtual hard disk (VHD) backing store file. Supports both sync and async modes.
        /// </summary>
        /// <param name="overlapped">If not null, the operation runs in async mode</param>
        public uint
        Compact(IntPtr overlapped) {
            return this.Compact(
                overlapped,
                NativeMethods.CompactVirtualDiskFlags.None);
        }
 
        /// <summary>
        /// Reduces the size of the virtual hard disk (VHD) backing store file. Supports both sync and async modes.
        /// </summary>
        /// <param name="overlapped">If not null, the operation runs in async mode</param>
        /// <param name="flags">Flags for Compact operation</param>
        public uint
        Compact(
            IntPtr overlapped,
            NativeMethods.CompactVirtualDiskFlags flags) {
 
            NativeMethods.CompactVirtualDiskParameters compactParams = new NativeMethods.CompactVirtualDiskParameters();
            compactParams.Version = NativeMethods.CompactVirtualDiskVersion.Version1;
 
            uint returnCode = NativeMethods.CompactVirtualDisk(
                m_virtualHardDiskHandle,
                flags,
            ref compactParams,
                overlapped);
 
            if ((overlapped == IntPtr.Zero && NativeMethods.ERROR_SUCCESS != returnCode) ||
                (overlapped != IntPtr.Zero && NativeMethods.ERROR_IO_PENDING != returnCode)) {
                throw new Win32Exception((int)returnCode);
            }
 
            return returnCode;
        }
 
 
        #endregion Public Methods
 
        #region Public Properties
 
        /// <summary>
        /// The SafeFileHandle object for the opened VHD.
        /// </summary>
        public SafeFileHandle
        VirtualHardDiskHandle {
            get {
                return m_virtualHardDiskHandle;
            }
        }
 
        /// <summary>
        /// Indicates the index of the disk when attached.
        /// If the virtual hard disk is not currently attached, -1 will be returned.
        /// </summary>
        public int
        DiskIndex {
            get {
                string path = PhysicalPath;
 
                if (null != path) {
 
                    Match match = Regex.Match(path, @"\d+$"); // look for the last digits in the path
                    return System.Convert.ToInt32(match.Value, CultureInfo.InvariantCulture);
                } else {
 
                    return -1;
                }
            }
        }
 
        /// <summary>
        /// Indicates whether the current Virtual Hard Disk is attached to the system.
        /// </summary>
        public bool
        IsAttached {
            get {
                return (this.DiskIndex != -1);
            }
        }
 
        /// <summary>
        /// Retrieves the path to the physical device object that contains a virtual hard disk (VHD), if the VHD is attached.
        /// If it is not attached, NULL will be returned.
        /// </summary>
        public string
        PhysicalPath {
            get {
                uint pathSize = 1024; // Isn't MAX_PATH 255?
                StringBuilder path = new StringBuilder((int)pathSize);
                uint returnCode = 0;
 
                returnCode = NativeMethods.GetVirtualDiskPhysicalPath(
                        m_virtualHardDiskHandle,
                    ref pathSize,
                        path);
 
                if (NativeMethods.ERROR_ERROR_DEV_NOT_EXIST == returnCode) {
 
                    return null;
                } else if (NativeMethods.ERROR_SUCCESS == returnCode) {
 
                    return path.ToString();
                } else {
 
                    throw new Win32Exception((int)returnCode);
                }
            }
        }
 
        #endregion Public Properties
    }
 
    #endregion VHD Interop
}
"@

Add-Type -TypeDefinition $code -ReferencedAssemblies 'System.Xml', 'System.Linq', 'System.Xml.Linq'
function Convert-Wim2VHD
{
  <#
    .Synopsis
    Create a VHDX and populate it from a WIM
    .DESCRIPTION
    This command will create a VHD or VHDX formated for UEFI (Gen 2/GPT) or BIOS (Gen 1/MBR)
    You must supply the path to the VHD/VHDX file and a valid WIM/ISO. You should also
    include the index number for the Windows Edition to install.
    .EXAMPLE
    Convert-WIM2VHDX -Path c:\windows8.vhdx -WimPath d:\Source\install.wim -Recovery -DiskLayout UEFI
    Create a a VHDX of the default size with GPT partitions used by UEFI (Gen2)
    .EXAMPLE
    Convert-WIM2VHDX -Path c:\windowsServer.vhdx -WimPath d:\Source\install.wim -index 3 -Size 40GB -force -DiskLayout UEFI
    Create a 40GB VHDX useing index 3 with Gpt partitions used by UEFI (Gen2)
    #>

  [CmdletBinding(SupportsShouldProcess = $true,
    PositionalBinding = $false,
    ConfirmImpact = 'Medium')]
  Param
  (
    # Path to the new VHDX file (Must end in .vhdx)
    [Parameter(Position = 0, Mandatory = $true,
      HelpMessage = 'Enter the path for the new VHDX file')]
    [ValidateNotNullorEmpty()]
    [ValidatePattern(".\.vhdx?$")]
    [ValidateScript( {
        if (Get-FullFilePath -Path $_ |
          Split-Path |
          Resolve-Path )
        {
          $true
        }
        else
        {
          Throw "Parent folder for $_ does not exist."
        }
      })]
    [string]$Path,

    # Size in Bytes (Default 40B)
    [ValidateRange(25GB, 64TB)]
    [long]$Size = 40GB,

    # Create Dynamic disk
    [switch]$Dynamic,

    # Specifies whether to build the image for BIOS (MBR), UEFI (GPT), or WindowsToGo (MBR).
    # Generation 1 VMs require BIOS (MBR) images. Generation 2 VMs require UEFI (GPT) images.
    # Windows To Go images will boot in UEFI or BIOS
    [Parameter(Mandatory = $true)]
    [Alias('Layout')]
    [string]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('BIOS', 'UEFI', 'WindowsToGo')]
    $DiskLayout,

    # Skip the creation of the Recovery Environment Tools Partition.
    [switch]$NoRecoveryTools,

    # System (boot loader) Partition Size (Default : 260MB)
    [int]$SystemSize,

    # MS Reserved Partition Size (Default : 128MB)
    [int]$ReservedSize,

    # Recovery Tools Partition Size (Default : 905MB)
    [int]$RecoverySize,

    # Force the overwrite of existing files
    [switch]$force,

    # Path to WIM or ISO used to populate VHDX
    [parameter(Position = 1, Mandatory = $true,
      HelpMessage = 'Enter the path to the WIM/ISO file')]
    [ValidateScript( {
        Test-Path -Path (Get-FullFilePath -Path $_ )
      })]
    [string]$SourcePath,

    # Index of image inside of WIM (Default 1)
    [int]$Index = 1,

    # Path to file to copy inside of VHD(X) as C:\unattent.xml
    [ValidateScript( {
        if ($_)
        {
          Test-Path -Path $_
        }
        else
        {
          $true
        }
      })]
    [string]$Unattend,

    # Native Boot does not have the boot code inside the VHD(x) it must exist on the physical disk.
    [switch]$NativeBoot,

    # Features to turn on (in DISM format)
    [ValidateNotNullOrEmpty()]
    [string[]]$Feature,

    # Feature to remove (in DISM format)
    [ValidateNotNullOrEmpty()]
    [string[]]$RemoveFeature,

    # Feature Source path. If not provided, all ISO and WIM images in $sourcePath searched
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        ($_ -eq 'NONE') -or (Test-Path -Path $(Resolve-Path $_))
      })]
    [string]$FeatureSource,

    # Feature Source index. If the source is a .wim provide an index Default =1
    [int]$FeatureSourceIndex = 1,

    # Path to drivers to inject
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        foreach ($Path in $_)
        {
          Test-Path -Path $(Resolve-Path $Path)
        }
      })]
    [string[]]$Driver,

    # Add payload for all removed features
    [switch]$AddPayloadForRemovedFeature,

    # Path of packages to install via DSIM
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        foreach ($Path in $_)
        {
          Test-Path -Path $(Resolve-Path $Path)
        }
      })]
    [string[]]$Package,
    # Files/Folders to copy to root of Winodws Drive (to place files in directories mimic the direcotry structure off of C:\)
    [ValidateNotNullOrEmpty()]
    [ValidateScript( {
        foreach ($Path in $_)
        {
          Test-Path -Path $(Resolve-Path $Path)
        }
      })]
    [string[]]$filesToInject

  )
  $Path = $Path | Get-FullFilePath
  $SourcePath = $SourcePath | Get-FullFilePath

  #$VhdxFileName = Split-Path -Leaf -Path $Path

  if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] : Overwrite partitions inside [$Path] with content of [$SourcePath]",
      "Overwrite partitions inside [$Path] with contentce of [$SourcePath]? ",
      'Overwrite WARNING!'))
  {
    if ((-not (Test-Path $Path)) -Or $force -Or $pscmdlet.ShouldContinue('Are you sure? Any existin data will be lost!', 'Warning'))
    {
      $ParametersToPass = @{ }
      foreach ($key in ('Whatif', 'Verbose', 'Debug'))
      {
        if ($PSBoundParameters.ContainsKey($key))
        {
          $ParametersToPass[$key] = $PSBoundParameters[$key]
        }
      }

      $InitializeVHDPartitionParam = @{
        'Size'       = $Size
        'Path'       = $Path
        'force'      = $true
        'DiskLayout' = $DiskLayout
      }
      if ($NoRecoveryTools)
      {
        $InitializeVHDPartitionParam.add('NoRecoveryTools', $true)
      }
      if ($Dynamic)
      {
        $InitializeVHDPartitionParam.add('Dynamic', $true)
      }
      if ($SystemSize) { $InitializeVHDPartitionParam.add('SystemSize', $SystemSize) }
      if ($ReservedSize) { $InitializeVHDPartitionParam.add('ReservedSize', $ReservedSize) }
      if ($RecoverySize) { $InitializeVHDPartitionParam.add('RecoverySize', $RecoverySize) }

      $SetVHDPartitionParam = @{
        'SourcePath' = $SourcePath
        'Path'       = $Path
        'Index'      = $Index
        'force'      = $true
        'Confirm'    = $false
      }
      if ($Unattend)
      {
        $SetVHDPartitionParam.add('Unattend', $Unattend)
      }
      if ($NativeBoot)
      {
        $SetVHDPartitionParam.add('NativeBoot', $NativeBoot)
      }
      if ($Feature)
      {
        $SetVHDPartitionParam.add('Feature', $Feature)
      }
      if ($RemoveFeature)
      {
        $SetVHDPartitionParam.add('RemoveFeature', $RemoveFeature)
      }
      if ($FeatureSource)
      {
        $SetVHDPartitionParam.add('FeatureSource', $FeatureSource)
      }
      if ($FeatureSourceIndex)
      {
        $SetVHDPartitionParam.add('FeatureSourceIndex', $FeatureSourceIndex)
      }
      if ($AddPayloadForRemovedFeature)
      {
        $SetVHDPartitionParam.add('AddPayloadForRemovedFeature', $AddPayloadForRemovedFeature)
      }
      if ($Driver)
      {
        $SetVHDPartitionParam.add('Driver', $Driver)
      }
      if ($Package)
      {
        $SetVHDPartitionParam.add('Package', $Package)
      }
      if ($filesToInject)
      {
        $SetVHDPartitionParam.add('filesToInject', $filesToInject)
      }
      Write-Verbose -Message "[$($MyInvocation.MyCommand)] : InitializeVHDPartitionParam"
      Write-Verbose -Message ($InitializeVHDPartitionParam | Out-String)
      Write-Verbose -Message "[$($MyInvocation.MyCommand)] : SetVHDPartitionParam"
      Write-Verbose -Message ($SetVHDPartitionParam | Out-String)
      Write-Verbose -Message "[$($MyInvocation.MyCommand)] : ParametersToPass"
      Write-Verbose -Message ($ParametersToPass | Out-String)

      Try
      {
        Initialize-VHDPartition @InitializeVHDPartitionParam @ParametersToPass
        Set-VHDPartition @SetVHDPartitionParam @ParametersToPass
      }
      Catch
      {
        throw "$($_.Exception.Message) at $($_.Exception.InvocationInfo.ScriptLineNumber)"
      }
    }
  }
}


function Initialize-DataDisk
{
    <#
    .Synopsis
    Partition GPT and Fomat as a Data Drive
    .DESCRIPTION
    This command will Partition and Format the disk as a Data Drive.
    .EXAMPLE
    Initialize-DataDisk -DiskNumber 1 -DataFormat ReFS
    .EXAMPLE
    Initialize-DataDisk -DiskNumber 1 -DataFormat NTFS
    #>

    [CmdletBinding(SupportsShouldProcess = $true,
        PositionalBinding = $false,
        ConfirmImpact = 'Medium')]
    Param
    (
        # Disk number, disk must exist
        [Parameter(Position = 0, Mandatory,
            HelpMessage = 'Disk Number based on Get-Disk')]
        [ValidateNotNullorEmpty()]
        [ValidateScript( {
                if (Get-Disk -Number $_)
                {
                    $true
                }
                else
                {
                    Throw "Disk number $_ does not exist."
                }
            })]
        [string]$DiskNumber,

        # Format drive as NTFS or ReFS (Only applies when DiskLayout = Data)
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('NTFS', 'ReFS')]
        $DataFormat = 'ReFS',

        # MS Reserved Partition Size (Default : 128MB)
        [int]$ReservedSize,

        # Force the overwrite of existing files
        [switch]$force
    )
    if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] : Overwrite partitions on disk [$DiskNumber]",
            "Overwrite partitions on disk [$DiskNumber]? ",
            'Overwrite WARNING!'))
    {
        if ((Get-Disk -Number $DiskNumber | Get-Partition -ErrorAction SilentlyContinue) -Or $force -Or $pscmdlet.ShouldContinue('Are you sure? Any existin data will be lost!', 'Warning'))
        {
            $ParametersToPass = @{ }
            foreach ($key in ('Whatif', 'Verbose', 'Debug'))
            {
                if ($PSBoundParameters.ContainsKey($key))
                {
                    $ParametersToPass[$key] = $PSBoundParameters[$key]
                }
            }

            $InitializeDiskPartitionParam = @{
                'DiskNumber' = $DiskNumber
                'force'      = $true
                'DiskLayout' = 'Data'
                'DataFormat' = $DataFormat
            }
            if ($ReservedSize)
            {
                $InitializeDiskPartitionParam.add('ReservedSize', $ReservedSize)
            }
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : InitializeDiskPartitionParam"
            Write-Verbose -Message ($InitializeVHDPartitionParam | Out-String)
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : ParametersToPass"
            Write-Verbose -Message ($ParametersToPass | Out-String)

            Try
            {
                Initialize-DiskPartition @InitializeDiskPartitionParam @ParametersToPass
            }
            Catch
            {
                throw "$($_.Exception.Message) at $($_.Exception.InvocationInfo.ScriptLineNumber)"
            }
            try
            {
                #! Workarround for new drive letters in script modules
                $null = Get-PSDrive

                #region Assign Drive Letters (disable explorer popup and reset afterwords)
                $DisableAutoPlayOldValue = (Get-ItemProperty -path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -name DisableAutoplay).DisableAutoplay
                Set-ItemProperty -Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -Value 1
                foreach ($partition in (Get-Partition -DiskNumber $DiskNumber |
                        where-object -FilterScript { $_.Type -eq 'IFS' -or $_.type -eq 'basic' }))
                {
                    $partition | Add-PartitionAccessPath -AssignDriveLetter -ErrorAction Stop
                }
                #! Workarround for new drive letters in script modules
                $null = Get-PSDrive
                Set-ItemProperty -Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -Value $DisableAutoPlayOldValue
            }
            catch
            {
                Write-Error -Message "[$($MyInvocation.MyCommand)] [$DiskNumber] : Error Adding Drive Letter "
                throw $_.Exception.Message
            }
        }
    }
}


function Install-WindowsFromWim
{
    <#
    .Synopsis
    Populate a Disk it from a WIM
    .DESCRIPTION
    This command will Format the disk and install Windows from a WIM/ISO
    You must supply the path to a valid WIM/ISO. You should also
    include the index number for the Windows Edition to install.
    .EXAMPLE
    Install-WindowsFromWim -DiskNumber 0 -WimPath d:\Source\install.wim -NoRecoveryTools -DiskLayout UEFI
    Installs Windows to Disk Number 0 with no Recovery Partition from Index 1
    .EXAMPLE
    Install-WindowsFromWim -DiskNumber 0 -WimPath d:\Source\install.wim -index 3 -force -DiskLayout UEFI
    Installs Windows to Disk Number 0 from with recoery partition from index 3 and overwrits any existing data.
    #>

    [CmdletBinding(SupportsShouldProcess = $true,
        PositionalBinding = $false,
        ConfirmImpact = 'Medium')]
    Param
    (
        # Disk number, disk must exist
        [Parameter(Position = 0, Mandatory,
            HelpMessage = 'Disk Number based on Get-Disk')]
        [ValidateNotNullorEmpty()]
        [ValidateScript( {
                if (Get-Disk -Number $_)
                {
                    $true
                }
                else
                {
                    Throw "Disk number $_ does not exist."
                }
            })]
        [string]$DiskNumber,

        # Specifies whether to build the image for BIOS (MBR), UEFI (GPT), or WindowsToGo (MBR).
        # Generation 1 VMs require BIOS (MBR) images. Generation 2 VMs require UEFI (GPT) images.
        # Windows To Go images will boot in UEFI or BIOS
        [Parameter(Mandatory = $true)]
        [Alias('Layout')]
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('BIOS', 'UEFI', 'WindowsToGo')]
        $DiskLayout,

        # Skip creating the Recovery Environment Tools Partition.
        [switch]$NoRecoveryTools,

        # System (boot loader) Partition Size (Default : 260MB)
        [int]$SystemSize,

        # MS Reserved Partition Size (Default : 128MB)
        [int]$ReservedSize,

        # Recovery Tools Partition Size (Default : 905MB)
        [int]$RecoverySize,

        # Force the overwrite of existing files
        [switch]$force,

        # Path to WIM or ISO used to populate VHDX
        [parameter(Position = 1, Mandatory = $true,
            HelpMessage = 'Enter the path to the WIM/ISO file')]
        [ValidateScript( {
                Test-Path -Path (Get-FullFilePath -Path $_ )
            })]
        [string]$SourcePath,

        # Index of image inside of WIM (Default 1)
        [int]$Index = 1,

        # Path to file to copy inside of VHD(X) as C:\unattent.xml
        [ValidateScript( {
                if ($_)
                {
                    Test-Path -Path $_
                }
                else
                {
                    $true
                }
            })]
        [string]$Unattend,

        # Native Boot does not have the boot code inside the VHD(x) it must exist on the physical disk.
        [switch]$NativeBoot,

        # Features to turn on (in DISM format)
        [ValidateNotNullOrEmpty()]
        [string[]]$Feature,

        # Feature to remove (in DISM format)
        [ValidateNotNullOrEmpty()]
        [string[]]$RemoveFeature,

        # Feature Source path. If not provided, all ISO and WIM images in $sourcePath searched
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                (Test-Path -Path $(Resolve-Path $_) -or ($_ -eq 'NONE') )
            })]
        [string]$FeatureSource,

        # Feature Source index. If the source is a .wim provide an index Default =1
        [int]$FeatureSourceIndex = 1,

        # Path to drivers to inject
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                foreach ($Path in $_)
                {
                    Test-Path -Path $(Resolve-Path $Path)
                }
            })]
        [string[]]$Driver,

        # Add payload for all removed features
        [switch]$AddPayloadForRemovedFeature,

        # Path of packages to install via DSIM
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                foreach ($Path in $_)
                {
                    Test-Path -Path $(Resolve-Path $Path)
                }
            })]
        [string[]]$Package,
        # Files/Folders to copy to root of Windows Drive (to place files in directories mimic the direcotry structure off of C:\)
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                foreach ($Path in $_)
                {
                    Test-Path -Path $(Resolve-Path $Path)
                }
            })]
        [string[]]$filesToInject

    )
    $SourcePath = $SourcePath | Get-FullFilePath

    if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] : Overwrite partitions on disk [$DiskNumber] with content of [$SourcePath]",
            "Overwrite partitions on disk [$DiskNumber] with contentce of [$SourcePath]? ",
            'Overwrite WARNING!'))
    {
        if ((Get-Disk -Number $DiskNumber | Get-Partition -ErrorAction SilentlyContinue) -Or $force -Or $pscmdlet.ShouldContinue('Are you sure? Any existin data will be lost!', 'Warning'))
        {
            $ParametersToPass = @{ }
            foreach ($key in ('Whatif', 'Verbose', 'Debug'))
            {
                if ($PSBoundParameters.ContainsKey($key))
                {
                    $ParametersToPass[$key] = $PSBoundParameters[$key]
                }
            }

            $InitializeDiskPartitionParam = @{
                'DiskNumber' = $DiskNumber
                'force'      = $true
                'DiskLayout' = $DiskLayout
            }
            if ($NoRecoveryTools)
            {
                $InitializeDiskPartitionParam.add('NoRecoveryTools', $true)
            }
            if ($Dynamic)
            {
                $InitializeDiskPartitionParam.add('Dynamic', $true)
            }
            if ($SystemSize) { $InitializeDiskPartitionParam.add('SystemSize', $SystemSize) }
            if ($ReservedSize) { $InitializeDiskPartitionParam.add('ReservedSize', $ReservedSize) }
            if ($RecoverySize) { $InitializeDiskPartitionParam.add('RecoverySize', $RecoverySize) }

            $SetDiskPartitionParam = @{
                'SourcePath' = $SourcePath
                'DiskNumber' = $DiskNumber
                'Index'      = $Index
                'force'      = $true
                'Confirm'    = $false
            }
            if ($Unattend)
            {
                $SetDiskPartitionParam.add('Unattend', $Unattend)
            }
            if ($NativeBoot)
            {
                $SetDiskPartitionParam.add('NativeBoot', $NativeBoot)
            }
            if ($Feature)
            {
                $SetDiskPartitionParam.add('Feature', $Feature)
            }
            if ($RemoveFeature)
            {
                $SetDiskPartitionParam.add('RemoveFeature', $RemoveFeature)
            }
            if ($FeatureSource)
            {
                $SetDiskPartitionParam.add('FeatureSource', $FeatureSource)
            }
            if ($FeatureSourceIndex)
            {
                $SetDiskPartitionParam.add('FeatureSourceIndex', $FeatureSourceIndex)
            }
            if ($AddPayloadForRemovedFeature)
            {
                $SetDiskPartitionParam.add('AddPayloadForRemovedFeature', $AddPayloadForRemovedFeature)
            }
            if ($Driver)
            {
                $SetDiskPartitionParam.add('Driver', $Driver)
            }
            if ($Package)
            {
                $SetDiskPartitionParam.add('Package', $Package)
            }
            if ($filesToInject)
            {
                $SetDiskPartitionParam.add('filesToInject', $filesToInject)
            }
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : InitializeDiskPartitionParam"
            Write-Verbose -Message ($InitializeVHDPartitionParam | Out-String)
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : SetDiskPartitionParam"
            Write-Verbose -Message ($SetDiskPartitionParam | Out-String)
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : ParametersToPass"
            Write-Verbose -Message ($ParametersToPass | Out-String)

            Try
            {
                Initialize-DiskPartition @InitializeDiskPartitionParam @ParametersToPass
                Set-DiskPartition @SetDiskPartitionParam @ParametersToPass
            }
            Catch
            {
                throw "$($_.Exception.Message) at $($_.Exception.InvocationInfo.ScriptLineNumber)"
            }
        }
    }
}


function New-DataVHD
{
    <#
    .Synopsis
    Create a VHDX Data Drive with GPT partitions
    .DESCRIPTION
    This command will create a VHD or VHDX with a GPT partition table
    formated ReFS(Default) or NTFS. You must supply the path to the VHD/VHDX file
    Use -Force to overwite existing file (ACLs will be copied to new file)
    .EXAMPLE
    New-DataVHD -Path c:\Data.vhdx -Size 20GB -Dynamic
    Creats a new 20GB Data VHDX that is dynamic, formated ReFS
    .EXAMPLE
    New-DataVHD -Path c:\data.vhdx -Size 100GB -DataFormat NTFS
    Creats a new 100GB Data VHDX formated NTFS
    #>

    [CmdletBinding(SupportsShouldProcess = $true,
        PositionalBinding = $false,
        ConfirmImpact = 'Medium')]
    Param
    (
        # Path to the new VHDX file (Must end in .vhdx)
        [Parameter(Position = 0, Mandatory = $true,
            HelpMessage = 'Enter the path for the new VHDX file')]
        [ValidateNotNullorEmpty()]
        [ValidatePattern(".\.vhdx?$")]
        [ValidateScript( {
                if (Get-FullFilePath -Path $_ |
                    Split-Path |
                    Resolve-Path )
                {
                    $true
                }
                else
                {
                    Throw "Parent folder for $_ does not exist."
                }
            })]
        [string]$Path,

        # Format drive as NTFS or ReFS (Only applies when DiskLayout = Data)
        [string]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('NTFS', 'ReFS')]
        $DataFormat = 'ReFS',

        # Size in Bytes (Default 40B)
        [ValidateRange(25GB, 64TB)]
        [long]$Size = 40GB,

        # MS Reserved Partition Size (Default : 128MB)
        [int]$ReservedSize,

        # Create Dynamic disk
        [switch]$Dynamic,

        # Force the overwrite of existing files
        [switch]$force

    )
    $Path = $Path | Get-FullFilePath
    $VhdxFileName = Split-Path -Leaf -Path $Path

    if ($pscmdlet.ShouldProcess("[$($MyInvocation.MyCommand)] : Overwrite partitions inside [$Path] with GPT Data Partitions",
            "Overwrite partitions inside [$Path] with GPT Data Partitions ? ",
            'Overwrite WARNING!'))
    {
        if ((-not (Test-Path $Path)) -Or $force -Or $pscmdlet.ShouldContinue('Are you sure? Any existin data will be lost!', 'Warning'))
        {
            $ParametersToPass = @{ }
            foreach ($key in ('Whatif', 'Verbose', 'Debug'))
            {
                if ($PSBoundParameters.ContainsKey($key))
                {
                    $ParametersToPass[$key] = $PSBoundParameters[$key]
                }
            }

            $InitializeVHDPartitionParam = @{
                'Size'       = $Size
                'Path'       = $Path
                'force'      = $true
                'DiskLayout' = 'Data'
                'DataFormat' = $DataFormat
            }
            if ($Dynamic)
            {
                $InitializeVHDPartitionParam.add('Dynamic', $true)
            }
            if ($ReservedSize)
            {
                $InitializeVHDPartitionParam.add('ReservedSize', $ReservedSize)
            }
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : InitializeVHDPartitionParam"
            Write-Verbose -Message ($InitializeVHDPartitionParam | Out-String)
            Write-Verbose -Message "[$($MyInvocation.MyCommand)] : ParametersToPass"
            Write-Verbose -Message ($ParametersToPass | Out-String)
            Try
            {
                Initialize-VHDPartition @InitializeVHDPartitionParam @ParametersToPass
            }
            Catch
            {
                throw "$($_.Exception.Message) at $($_.Exception.InvocationInfo.ScriptLineNumber)"
            }
            #region mount the VHDX file
            try
            {
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Mounting disk image [$Path]"
                $disk = Mount-DiskImage -ImagePath $Path -PassThru |
                Get-DiskImage |
                Get-Disk
                $DiskNumber = $disk.Number
            }
            catch
            {
                throw $_.Exception.Message
            }
            #endregion

            try
            {
                #! Workarround for new drive letters in script modules
                $null = Get-PSDrive

                #region Assign Drive Letters (disable explorer popup and reset afterwords)
                $DisableAutoPlayOldValue = (Get-ItemProperty -path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -name DisableAutoplay).DisableAutoplay
                Set-ItemProperty -Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -Value 1
                foreach ($partition in (Get-Partition -DiskNumber $DiskNumber |
                        where-object -FilterScript { $_.Type -eq 'IFS' -or $_.type -eq 'basic' }))
                {
                    $partition | Add-PartitionAccessPath -AssignDriveLetter -ErrorAction Stop
                }
                #! Workarround for new drive letters in script modules
                $null = Get-PSDrive
                Set-ItemProperty -Path hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers -Name DisableAutoplay -Value $DisableAutoPlayOldValue
            }
            catch
            {
                Write-Error -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Error Adding Drive Letter "
                throw $_.Exception.Message
            }
            finally
            {
                #dismount
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Dismounting"
                $null = Dismount-DiskImage -ImagePath $Path
                if ($isoPath -and (Get-DiskImage $isoPath).Attached)
                {
                    $null = Dismount-DiskImage -ImagePath $isoPath
                    [System.GC]::Collect()
                }
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] [$VhdxFileName] : Finished"
            }
        }
    }
}
function New-UnattendXml {
    <#
    .Synopsis
    Create a new Unattend.xml
    .DESCRIPTION
    This Command Creates a new Unattend.xml that skips any prompts, and sets the administrator password
    Has options for:
      Joining domain
      Adding user accounts
      Auto logon a set number of times
      Set the Computer Name
      First Boot or First Logon powersrhell script
      Product Key
      TimeZone
      Input, System and User Locals
      UI Language
      Registered Owner and Orginization
      First Boot, First Logon and Every Logon Commands
      Enable Administrator account without autologon (client OS)
 
    If no Path is provided a the file will be created in a temp folder and the path returned.
    .EXAMPLE
    New-UnattendXml -AdminPassword 'P@ssword' -logonCount 1
    .EXAMPLE
    New-UnattendXml -Path c:\temp\Unattent.xml -AdminPassword 'P@ssword' -logonCount 100 -FirstLogonScriptPath c:\pstemp\firstrun.ps1
  #>

    [CmdletBinding(DefaultParameterSetName = 'Basic_FirstLogonScript',
        SupportsShouldProcess = $true)]
    [OutputType([System.IO.FileInfo])]
    Param
    (
        # The password to have unattnd.xml set the local Administrator to (minimum lenght 8)
        [Parameter(Mandatory = $true, HelpMessage = 'Local Administrator Credentials',
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias('AdminPassword')]
        [System.Management.Automation.Credential()][PSCredential]
        $AdminCredential,

        # User account/password to create and add to Administators group
        [System.Management.Automation.Credential()][PSCredential[]]
        $UserAccount,

        # User account/password to join do the domain
        [System.Management.Automation.Credential()][PSCredential]
        $JoinAccount,

        # Domain to join
        [string]
        $domain,

        # OU to place computer account into
        [string]
        $OU,

        # Output Path
        [Alias('FilePath', 'FullName', 'pspath', 'outfile')]
        [string]
        $Path = "$(New-TemporaryDirectory)\unattend.xml",

        # Number of times that the local Administrator account should automaticaly login (default 0)
        [ValidateRange(0, 1000)]
        [int]
        $LogonCount,

        # ComputerName (default = *)
        [ValidateLength(1, 15)]
        [string]
        $ComputerName = '*',

        # PowerShell Script to run on FirstLogon (ie. %SystemDrive%\PSTemp\FirstRun.ps1 )
        [Parameter(ParameterSetName = 'Basic_FirstLogonScript')]
        [string]
        $FirstLogonScriptPath,

        # PowerShell Script to run on FirstBoot (ie.: %SystemDrive%\PSTemp\FirstRun.ps1 ) Executed in system context during specialize phase
        [Parameter(ParameterSetName = 'Basic_FirstBootScript')]
        [string]
        $FirstBootScriptPath,

        # The product key to use for the unattended installation.
        [ValidatePattern('^[A-Z0-9]{5,5}-[A-Z0-9]{5,5}-[A-Z0-9]{5,5}-[A-Z0-9]{5,5}-[A-Z0-9]{5,5}$')]
        [string]
        $ProductKey,

        # Timezone (default: Central Standard Time)
        [ValidateSet('Dateline Standard Time',
            'UTC-11',
            'Hawaiian Standard Time',
            'Alaskan Standard Time',
            'Pacific Standard Time (Mexico)',
            'Pacific Standard Time',
            'US Mountain Standard Time',
            'Mountain Standard Time (Mexico)',
            'Mountain Standard Time',
            'Central America Standard Time',
            'Central Standard Time',
            'Central Standard Time (Mexico)',
            'Canada Central Standard Time',
            'SA Pacific Standard Time',
            'Eastern Standard Time (Mexico)',
            'Eastern Standard Time',
            'US Eastern Standard Time',
            'Venezuela Standard Time',
            'Paraguay Standard Time',
            'Atlantic Standard Time',
            'Central Brazilian Standard Time',
            'SA Western Standard Time',
            'Newfoundland Standard Time',
            'E. South America Standard Time',
            'SA Eastern Standard Time',
            'Argentina Standard Time',
            'Greenland Standard Time',
            'Montevideo Standard Time',
            'Bahia Standard Time',
            'Pacific SA Standard Time',
            'UTC-02',
            'Mid-Atlantic Standard Time',
            'Azores Standard Time',
            'Cape Verde Standard Time',
            'Morocco Standard Time',
            'UTC',
            'GMT Standard Time',
            'Greenwich Standard Time',
            'W. Europe Standard Time',
            'Central Europe Standard Time',
            'Romance Standard Time',
            'Central European Standard Time',
            'W. Central Africa Standard Time',
            'Namibia Standard Time',
            'Jordan Standard Time',
            'GTB Standard Time',
            'Middle East Standard Time',
            'Egypt Standard Time',
            'Syria Standard Time',
            'E. Europe Standard Time',
            'South Africa Standard Time',
            'FLE Standard Time',
            'Turkey Standard Time',
            'Israel Standard Time',
            'Kaliningrad Standard Time',
            'Libya Standard Time',
            'Arabic Standard Time',
            'Arab Standard Time',
            'Belarus Standard Time',
            'Russian Standard Time',
            'E. Africa Standard Time',
            'Iran Standard Time',
            'Arabian Standard Time',
            'Azerbaijan Standard Time',
            'Russia Time Zone 3',
            'Mauritius Standard Time',
            'Georgian Standard Time',
            'Caucasus Standard Time',
            'Afghanistan Standard Time',
            'West Asia Standard Time',
            'Ekaterinburg Standard Time',
            'Pakistan Standard Time',
            'India Standard Time',
            'Sri Lanka Standard Time',
            'Nepal Standard Time',
            'Central Asia Standard Time',
            'Bangladesh Standard Time',
            'N. Central Asia Standard Time',
            'Myanmar Standard Time',
            'SE Asia Standard Time',
            'North Asia Standard Time',
            'China Standard Time',
            'North Asia East Standard Time',
            'Singapore Standard Time',
            'W. Australia Standard Time',
            'Taipei Standard Time',
            'Ulaanbaatar Standard Time',
            'North Korea Standard Time',
            'Tokyo Standard Time',
            'Korea Standard Time',
            'Yakutsk Standard Time',
            'Cen. Australia Standard Time',
            'AUS Central Standard Time',
            'E. Australia Standard Time',
            'AUS Eastern Standard Time',
            'West Pacific Standard Time',
            'Tasmania Standard Time',
            'Magadan Standard Time',
            'Vladivostok Standard Time',
            'Russia Time Zone 10',
            'Central Pacific Standard Time',
            'Russia Time Zone 11',
            'New Zealand Standard Time',
            'UTC+12',
            'Fiji Standard Time',
            'Kamchatka Standard Time',
            'Tonga Standard Time',
            'Samoa Standard Time',
            'Line Islands Standard Time')]
        [string]
        $TimeZone,

        # Specifies the system input locale and the keyboard layout (default: en-US)
        [Parameter(ValueFromPipelineByPropertyName)]
        [ValidateSet('en-US',
            'nl-NL',
            'fr-FR',
            'de-DE',
            'it-IT',
            'ja-JP',
            'es-ES',
            'ar-SA',
            'zh-CN',
            'zh-HK',
            'zh-TW',
            'cs-CZ',
            'da-DK',
            'fi-FI',
            'el-GR',
            'he-IL',
            'hu-HU',
            'ko-KR',
            'nb-NO',
            'pl-PL',
            'pt-BR',
            'pt-PT',
            'ru-RU',
            'sv-SE',
            'tr-TR',
            'bg-BG',
            'hr-HR',
            'et-EE',
            'lv-LV',
            'lt-LT',
            'ro-RO',
            'sr-Latn-CS',
            'sk-SK',
            'sl-SI',
            'th-TH',
            'uk-UA',
            'af-ZA',
            'sq-AL',
            'am-ET',
            'hy-AM',
            'as-IN',
            'az-Latn-AZ',
            'eu-ES',
            'be-BY',
            'bn-BD',
            'bn-IN',
            'bs-Cyrl-BA',
            'bs-Latn-BA',
            'ca-ES',
            'fil-PH',
            'gl-ES',
            'ka-GE',
            'gu-IN',
            'ha-Latn-NG',
            'hi-IN',
            'is-IS',
            'ig-NG',
            'id-ID',
            'iu-Latn-CA',
            'ga-IE',
            'xh-ZA',
            'zu-ZA',
            'kn-IN',
            'kk-KZ',
            'km-KH',
            'rw-RW',
            'sw-KE',
            'kok-IN',
            'ky-KG',
            'lo-LA',
            'lb-LU',
            'mk-MK',
            'ms-BN',
            'ms-MY',
            'ml-IN',
            'mt-MT',
            'mi-NZ',
            'mr-IN',
            'ne-NP',
            'nn-NO',
            'or-IN',
            'ps-AF',
            'fa-IR',
            'pa-IN',
            'quz-PE',
            'sr-Cyrl-CS',
            'nso-ZA',
            'tn-ZA',
            'si-LK',
            'ta-IN',
            'tt-RU',
            'te-IN',
            'ur-PK',
            'uz-Latn-UZ',
            'vi-VN',
            'cy-GB',
            'wo-SN',
            'yo-NG')]
        [Alias('keyboardlayout')]
        [String]
        $InputLocale,

        # Specifies the language for non-Unicode programs (default: en-US)
        [ValidateSet('en-US',
            'nl-NL',
            'fr-FR',
            'de-DE',
            'it-IT',
            'ja-JP',
            'es-ES',
            'ar-SA',
            'zh-CN',
            'zh-HK',
            'zh-TW',
            'cs-CZ',
            'da-DK',
            'fi-FI',
            'el-GR',
            'he-IL',
            'hu-HU',
            'ko-KR',
            'nb-NO',
            'pl-PL',
            'pt-BR',
            'pt-PT',
            'ru-RU',
            'sv-SE',
            'tr-TR',
            'bg-BG',
            'hr-HR',
            'et-EE',
            'lv-LV',
            'lt-LT',
            'ro-RO',
            'sr-Latn-CS',
            'sk-SK',
            'sl-SI',
            'th-TH',
            'uk-UA',
            'af-ZA',
            'sq-AL',
            'am-ET',
            'hy-AM',
            'as-IN',
            'az-Latn-AZ',
            'eu-ES',
            'be-BY',
            'bn-BD',
            'bn-IN',
            'bs-Cyrl-BA',
            'bs-Latn-BA',
            'ca-ES',
            'fil-PH',
            'gl-ES',
            'ka-GE',
            'gu-IN',
            'ha-Latn-NG',
            'hi-IN',
            'is-IS',
            'ig-NG',
            'id-ID',
            'iu-Latn-CA',
            'ga-IE',
            'xh-ZA',
            'zu-ZA',
            'kn-IN',
            'kk-KZ',
            'km-KH',
            'rw-RW',
            'sw-KE',
            'kok-IN',
            'ky-KG',
            'lo-LA',
            'lb-LU',
            'mk-MK',
            'ms-BN',
            'ms-MY',
            'ml-IN',
            'mt-MT',
            'mi-NZ',
            'mr-IN',
            'ne-NP',
            'nn-NO',
            'or-IN',
            'ps-AF',
            'fa-IR',
            'pa-IN',
            'quz-PE',
            'sr-Cyrl-CS',
            'nso-ZA',
            'tn-ZA',
            'si-LK',
            'ta-IN',
            'tt-RU',
            'te-IN',
            'ur-PK',
            'uz-Latn-UZ',
            'vi-VN',
            'cy-GB',
            'wo-SN',
            'yo-NG')]
        [Parameter(ValueFromPipelineByPropertyName)]
        [String]
        $SystemLocale,

        # Specifies the per-user settings used for formatting dates, times, currency and numbers (default: en-US)
        [ValidateSet('en-US',
            'nl-NL',
            'fr-FR',
            'de-DE',
            'it-IT',
            'ja-JP',
            'es-ES',
            'ar-SA',
            'zh-CN',
            'zh-HK',
            'zh-TW',
            'cs-CZ',
            'da-DK',
            'fi-FI',
            'el-GR',
            'he-IL',
            'hu-HU',
            'ko-KR',
            'nb-NO',
            'pl-PL',
            'pt-BR',
            'pt-PT',
            'ru-RU',
            'sv-SE',
            'tr-TR',
            'bg-BG',
            'hr-HR',
            'et-EE',
            'lv-LV',
            'lt-LT',
            'ro-RO',
            'sr-Latn-CS',
            'sk-SK',
            'sl-SI',
            'th-TH',
            'uk-UA',
            'af-ZA',
            'sq-AL',
            'am-ET',
            'hy-AM',
            'as-IN',
            'az-Latn-AZ',
            'eu-ES',
            'be-BY',
            'bn-BD',
            'bn-IN',
            'bs-Cyrl-BA',
            'bs-Latn-BA',
            'ca-ES',
            'fil-PH',
            'gl-ES',
            'ka-GE',
            'gu-IN',
            'ha-Latn-NG',
            'hi-IN',
            'is-IS',
            'ig-NG',
            'id-ID',
            'iu-Latn-CA',
            'ga-IE',
            'xh-ZA',
            'zu-ZA',
            'kn-IN',
            'kk-KZ',
            'km-KH',
            'rw-RW',
            'sw-KE',
            'kok-IN',
            'ky-KG',
            'lo-LA',
            'lb-LU',
            'mk-MK',
            'ms-BN',
            'ms-MY',
            'ml-IN',
            'mt-MT',
            'mi-NZ',
            'mr-IN',
            'ne-NP',
            'nn-NO',
            'or-IN',
            'ps-AF',
            'fa-IR',
            'pa-IN',
            'quz-PE',
            'sr-Cyrl-CS',
            'nso-ZA',
            'tn-ZA',
            'si-LK',
            'ta-IN',
            'tt-RU',
            'te-IN',
            'ur-PK',
            'uz-Latn-UZ',
            'vi-VN',
            'cy-GB',
            'wo-SN',
            'yo-NG')]
        [Parameter(ValueFromPipelineByPropertyName)]
        [String]
        $UserLocale,

        # Specifies the system default user interface (UI) language (default: en-US)
        [ValidateSet('en-US',
            'nl-NL',
            'fr-FR',
            'de-DE',
            'it-IT',
            'ja-JP',
            'es-ES',
            'ar-SA',
            'zh-CN',
            'zh-HK',
            'zh-TW',
            'cs-CZ',
            'da-DK',
            'fi-FI',
            'el-GR',
            'he-IL',
            'hu-HU',
            'ko-KR',
            'nb-NO',
            'pl-PL',
            'pt-BR',
            'pt-PT',
            'ru-RU',
            'sv-SE',
            'tr-TR',
            'bg-BG',
            'hr-HR',
            'et-EE',
            'lv-LV',
            'lt-LT',
            'ro-RO',
            'sr-Latn-CS',
            'sk-SK',
            'sl-SI',
            'th-TH',
            'uk-UA',
            'af-ZA',
            'sq-AL',
            'am-ET',
            'hy-AM',
            'as-IN',
            'az-Latn-AZ',
            'eu-ES',
            'be-BY',
            'bn-BD',
            'bn-IN',
            'bs-Cyrl-BA',
            'bs-Latn-BA',
            'ca-ES',
            'fil-PH',
            'gl-ES',
            'ka-GE',
            'gu-IN',
            'ha-Latn-NG',
            'hi-IN',
            'is-IS',
            'ig-NG',
            'id-ID',
            'iu-Latn-CA',
            'ga-IE',
            'xh-ZA',
            'zu-ZA',
            'kn-IN',
            'kk-KZ',
            'km-KH',
            'rw-RW',
            'sw-KE',
            'kok-IN',
            'ky-KG',
            'lo-LA',
            'lb-LU',
            'mk-MK',
            'ms-BN',
            'ms-MY',
            'ml-IN',
            'mt-MT',
            'mi-NZ',
            'mr-IN',
            'ne-NP',
            'nn-NO',
            'or-IN',
            'ps-AF',
            'fa-IR',
            'pa-IN',
            'quz-PE',
            'sr-Cyrl-CS',
            'nso-ZA',
            'tn-ZA',
            'si-LK',
            'ta-IN',
            'tt-RU',
            'te-IN',
            'ur-PK',
            'uz-Latn-UZ',
            'vi-VN',
            'cy-GB',
            'wo-SN',
            'yo-NG')]
        [Parameter(ValueFromPipelineByPropertyName)]
        [String]
        $UILanguage,

        # Registered Owner (default: 'Valued Customer')
        [Parameter(ValueFromPipelineByPropertyName)]
        [ValidateNotNull()]
        [String]
        $RegisteredOwner,

        # Registered Organization (default: 'Valued Customer')
        [Parameter(ValueFromPipelineByPropertyName)]
        [ValidateNotNull()]
        [String]
        $RegisteredOrganization,

        # Array of hashtables with Description, Order, and Path keys, and optional Domain, Password(plain text), username keys. Executed by in the system context
        [Parameter(ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'Advanced')]
        [Hashtable[]]
        $FirstBootExecuteCommand,

        # Array of hashtables with Description, Order and CommandLine keys. Execuded at first logon of an Administrator, will auto elivate
        [Parameter(ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'Advanced')]
        [Hashtable[]]
        $FirstLogonExecuteCommand,

        # Array of hashtables with Description, Order and CommandLine keys. Executed at every logon, does not elivate.
        [Parameter(ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'Advanced')]
        [Hashtable[]]
        $EveryLogonExecuteCommand,

        # Enable Local Administrator account (default $true) this is needed for client OS if your not useing autologon or adding aditional admin users.
        [switch]
        $enableAdministrator
    )

    Begin {
        $templateUnattendXml = [xml] @'
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
  <settings pass="specialize">
    <component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></component>
    <component name="Microsoft-Windows-UnattendedJoin" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></component>
    <component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></component>
        <component name="Microsoft-Windows-Deployment" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></component>
        <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></component>
        <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></component>
  </settings>
  <settings pass="oobeSystem">
        <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <InputLocale>en-US</InputLocale>
          <SystemLocale>en-US</SystemLocale>
          <UILanguage>en-US</UILanguage>
          <UserLocale>en-US</UserLocale>
    </component>
        <component name="Microsoft-Windows-International-Core" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <InputLocale>en-US</InputLocale>
          <SystemLocale>en-US</SystemLocale>
          <UILanguage>en-US</UILanguage>
          <UserLocale>en-US</UserLocale>
    </component>
    <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <OOBE>
        <HideEULAPage>true</HideEULAPage>
        <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
        <NetworkLocation>Work</NetworkLocation>
        <ProtectYourPC>1</ProtectYourPC>
                <SkipUserOOBE>true</SkipUserOOBE>
                <SkipMachineOOBE>true</SkipMachineOOBE>
      </OOBE>
      <TimeZone>GMT Standard Time</TimeZone>
      <UserAccounts>
        <AdministratorPassword>
            <Value></Value>
            <PlainText>false</PlainText>
        </AdministratorPassword>
      </UserAccounts>
      <RegisteredOrganization>Generic Organization</RegisteredOrganization>
      <RegisteredOwner>Generic Owner</RegisteredOwner>
      </component>
        <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <OOBE>
        <HideEULAPage>true</HideEULAPage>
        <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
        <NetworkLocation>Work</NetworkLocation>
        <ProtectYourPC>1</ProtectYourPC>
                <SkipUserOOBE>true</SkipUserOOBE>
                <SkipMachineOOBE>true</SkipMachineOOBE>
      </OOBE>
      <TimeZone>GMT Standard Time</TimeZone>
      <UserAccounts>
        <AdministratorPassword>
            <Value></Value>
            <PlainText>false</PlainText>
        </AdministratorPassword>
      </UserAccounts>
      <RegisteredOrganization>Generic Organization</RegisteredOrganization>
      <RegisteredOwner>Generic Owner</RegisteredOwner>
    </component>
  </settings>
</unattend>
'@


        if ($LogonCount -gt 0) {
            Write-Warning -Message '-Autologon places the Administrator password in plain txt'
        }
    }
    Process {
        if ($pscmdlet.ShouldProcess("$path", 'Create new Unattended.xml')) {
            if ($FirstBootScriptPath) {
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding PowerShell script to First boot command"
                $FirstBootExecuteCommand = @(@{
                        Description = 'PowerShell First boot script'
                        order       = 1
                        path        = "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$FirstBootScriptPath`""
                    })
            }

            if ($FirstLogonScriptPath) {
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding PowerShell script to First Logon command"
                $FirstLogonExecuteCommand = @(@{
                        Description = 'PowerShell First logon script'
                        order       = 1
                        CommandLine = "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$FirstBootScriptPath`""
                    })
            }

            if ($enableAdministrator) {
                Write-Verbose -Message "[$($MyInvocation.MyCommand)] Enabeling Administrator via First boot command"
                if ($FirstBootExecuteCommand) {
                    $FirstBootExecuteCommand = $FirstBootExecuteCommand + @{
                        Description = 'Enable Administrator'
                        order       = 0
                        path        = 'net user administrator /active:yes'
                    }
                } else {
                    $FirstBootExecuteCommand = @{
                        Description = 'Enable Administrator'
                        order       = 0
                        path        = 'net user administrator /active:yes'
                    }
                }
            } else {
                if ((-not ($UserAccount)) -or (-not($EnableAdministrator)) -or ( (-not ($domain)) -and (-not ($JoinAccount)) -and (-not ($OU)) ) ) {
                    Write-Warning -Message "$Path only usable on a server SKU, for a client OS, use either -EnableAdministrator or -UserAccount, or (-Domain and -JoinAccount and -OU)"
                }
            }

            [xml] $unattendXml = $templateUnattendXml
            foreach ($setting in $unattendXml.Unattend.Settings) {
                foreach ($component in $setting.Component) {
                    if ($setting.'Pass' -eq 'specialize' -and $component.'Name' -eq 'Microsoft-Windows-UnattendedJoin' ) {
                        if (($JoinAccount) -or ($domain) -or ($OU)) {
                            if (($JoinAccount) -and ($domain) -and ($OU)) {
                                Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Unattend Domain Join for $($component.'processorArchitecture') Architecture"
                                $identificationElement = $component.AppendChild($unattendXml.CreateElement('Identification', 'urn:schemas-microsoft-com:unattend'))
                                $IdCredentialElement = $identificationElement.AppendChild($unattendXml.CreateElement('Credentials', 'urn:schemas-microsoft-com:unattend'))
                                $IdCredDomainEliment = $IdCredentialElement.AppendChild($unattendXml.CreateElement('Domain', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $IdCredDomainEliment.AppendChild($unattendXml.CreateTextNode($domain))
                                $IdCredPasswordElement = $IdCredentialElement.AppendChild($unattendXml.CreateElement('Password', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $IdCredPasswordElement.AppendChild($unattendXml.CreateTextNode($JoinAccount.GetNetworkCredential().Password))
                                $IdCredUserNameElement = $IdCredentialElement.AppendChild($unattendXml.CreateElement('Username', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $IdCredUserNameElement.AppendChild($unattendXml.CreateTextNode($JoinAccount.GetNetworkCredential().UserName))
                                $IdJoinDomainElement = $identificationElement.AppendChild($unattendXml.CreateElement('JoinDomain', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $IdJoinDomainElement.AppendChild($unattendXml.CreateTextNode($domain))
                                $IdMachineOUElement = $identificationElement.AppendChild($unattendXml.CreateElement('MachineObjectOU', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $IdMachineOUElement.AppendChild($unattendXml.CreateTextNode($OU))
                                $IdUnsecureJoinElement = $identificationElement.AppendChild($unattendXml.CreateElement('UnsecureJoin', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $IdUnsecureJoinElement.AppendChild($unattendXml.CreateTextNode('False'))

                            } else {
                                Write-Warning 'Domain join requires -JoinAccount, -Domain, and -OU : one or more is missing, skipping section'
                            }

                        }
                    }
                    if ($setting.'Pass' -eq 'specialize' -and $component.'Name' -eq 'Microsoft-Windows-Deployment' ) {
                        if (($null -ne $FirstBootExecuteCommand -or $FirstBootExecuteCommand.Length -gt 0) -and $component.'processorArchitecture' -eq 'x86') {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding first boot command(s)"
                            $commandOrder = 1
                            $runSynchronousElement = $component.AppendChild($unattendXml.CreateElement('RunSynchronous', 'urn:schemas-microsoft-com:unattend'))
                            foreach ($synchronousCommand in ($FirstBootExecuteCommand | Sort-Object -Property {
                                        $_.order
                                    })) {
                                $syncCommandElement = $runSynchronousElement.AppendChild($unattendXml.CreateElement('RunSynchronousCommand', 'urn:schemas-microsoft-com:unattend'))
                                $null = $syncCommandElement.SetAttribute('action', 'http://schemas.microsoft.com/WMIConfig/2002/State', 'add')
                                $syncCommandDescriptionElement = $syncCommandElement.AppendChild($unattendXml.CreateElement('Description', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $syncCommandDescriptionElement.AppendChild($unattendXml.CreateTextNode($synchronousCommand['Description']))
                                $syncCommandOrderElement = $syncCommandElement.AppendChild($unattendXml.CreateElement('Order', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $syncCommandOrderElement.AppendChild($unattendXml.CreateTextNode($commandOrder))
                                $syncCommandPathElement = $syncCommandElement.AppendChild($unattendXml.CreateElement('Path', 'urn:schemas-microsoft-com:unattend'))
                                $Null = $syncCommandPathElement.AppendChild($unattendXml.CreateTextNode($synchronousCommand['Path']))
                                $commandOrder++
                            }
                        }
                    }
                    if (($setting.'Pass' -eq 'specialize') -and ($component.'Name' -eq 'Microsoft-Windows-Shell-Setup')) {
                        if ($ComputerName) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding custom computername for $($component.'processorArchitecture') Architecture"
                            $computerNameElement = $component.AppendChild($unattendXml.CreateElement('ComputerName', 'urn:schemas-microsoft-com:unattend'))
                            $Null = $computerNameElement.AppendChild($unattendXml.CreateTextNode($ComputerName))
                        }
                        if ($ProductKey) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Product key for $($component.'processorArchitecture') Architecture"
                            $productKeyElement = $component.AppendChild($unattendXml.CreateElement('ProductKey', 'urn:schemas-microsoft-com:unattend'))
                            $Null = $productKeyElement.AppendChild($unattendXml.CreateTextNode($ProductKey.ToUpper()))
                        }
                    }

                    if (($setting.'Pass' -eq 'oobeSystem') -and ($component.'Name' -eq 'Microsoft-Windows-International-Core')) {
                        if ($InputLocale) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Input Locale for $($component.'processorArchitecture') Architecture"
                            $component.InputLocale = $InputLocale
                        }
                        if ($SystemLocale) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding System Locale for $($component.'processorArchitecture') Architecture"
                            $component.SystemLocale = $SystemLocale
                        }
                        if ($UILanguage) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding UI Language for $($component.'processorArchitecture') Architecture"
                            $component.UILanguage = $UILanguage
                        }
                        if ($UserLocale) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding User Locale for $($component.'processorArchitecture') Architecture"
                            $component.UserLocale = $UserLocale
                        }
                    }

                    if (($setting.'Pass' -eq 'oobeSystem') -and ($component.'Name' -eq 'Microsoft-Windows-Shell-Setup')) {
                        if ($TimeZone) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Time Zone for $($component.'processorArchitecture') Architecture"
                            $component.TimeZone = $TimeZone
                        }
                        Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Administrator Passwords for $($component.'processorArchitecture') Architecture"
                        $concatenatedPassword = '{0}AdministratorPassword' -f $AdminCredential.GetNetworkCredential().password
                        $component.UserAccounts.AdministratorPassword.Value = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($concatenatedPassword))
                        if ($RegisteredOrganization) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Registred Organization for $($component.'processorArchitecture') Architecture"
                            $component.RegisteredOrganization = $RegisteredOrganization
                        }
                        if ($RegisteredOwner) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Registered Owner for $($component.'processorArchitecture') Architecture"
                            $component.RegisteredOwner = $RegisteredOwner
                        }
                        if ($UserAccount) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding User Account(s) for $($component.'processorArchitecture') Architecture"
                            $UserAccountsElement = $component.UserAccounts
                            $LocalAccountsElement = $UserAccountsElement.AppendChild($unattendXml.CreateElement('LocalAccounts', 'urn:schemas-microsoft-com:unattend'))
                            foreach ($Account in $UserAccount) {
                                $LocalAccountElement = $LocalAccountsElement.AppendChild($unattendXml.CreateElement('LocalAccount', 'urn:schemas-microsoft-com:unattend'))
                                $LocalAccountPasswordElement = $LocalAccountElement.AppendChild($unattendXml.CreateElement('Password', 'urn:schemas-microsoft-com:unattend'))
                                $LocalAccountPasswordValueElement = $LocalAccountPasswordElement.AppendChild($unattendXml.CreateElement('Value', 'urn:schemas-microsoft-com:unattend'))
                                $LocalAccountPasswordPlainTextElement = $LocalAccountPasswordElement.AppendChild($unattendXml.CreateElement('PlainText', 'urn:schemas-microsoft-com:unattend'))
                                $LocalAccountDisplayNameElement = $LocalAccountElement.AppendChild($unattendXml.CreateElement('DisplayName', 'urn:schemas-microsoft-com:unattend'))
                                $LocalAccountGroupElement = $LocalAccountElement.AppendChild($unattendXml.CreateElement('Group', 'urn:schemas-microsoft-com:unattend'))
                                $LocalAccountNameElement = $LocalAccountElement.AppendChild($unattendXml.CreateElement('Name', 'urn:schemas-microsoft-com:unattend'))

                                $null = $LocalAccountElement.SetAttribute('action', 'http://schemas.microsoft.com/WMIConfig/2002/State', 'add')
                                $concatenatedPassword = '{0}Password' -f $Account.GetNetworkCredential().password
                                $null = $LocalAccountPasswordValueElement.AppendChild($unattendXml.CreateTextNode([System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($concatenatedPassword))))
                                $null = $LocalAccountPasswordPlainTextElement.AppendChild($unattendXml.CreateTextNode('false'))
                                $null = $LocalAccountDisplayNameElement.AppendChild($unattendXml.CreateTextNode($Account.UserName))
                                $null = $LocalAccountGroupElement.AppendChild($unattendXml.CreateTextNode('Administrators'))
                                $null = $LocalAccountNameElement.AppendChild($unattendXml.CreateTextNode($Account.UserName))
                            }
                        }

                        if ($LogonCount) {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Autologon for $($component.'processorArchitecture') Architecture"
                            $autoLogonElement = $component.AppendChild($unattendXml.CreateElement('AutoLogon', 'urn:schemas-microsoft-com:unattend'))
                            $autoLogonPasswordElement = $autoLogonElement.AppendChild($unattendXml.CreateElement('Password', 'urn:schemas-microsoft-com:unattend'))
                            $autoLogonPasswordValueElement = $autoLogonPasswordElement.AppendChild($unattendXml.CreateElement('Value', 'urn:schemas-microsoft-com:unattend'))
                            $autoLogonCountElement = $autoLogonElement.AppendChild($unattendXml.CreateElement('LogonCount', 'urn:schemas-microsoft-com:unattend'))
                            $autoLogonUsernameElement = $autoLogonElement.AppendChild($unattendXml.CreateElement('Username', 'urn:schemas-microsoft-com:unattend'))
                            $autoLogonEnabledElement = $autoLogonElement.AppendChild($unattendXml.CreateElement('Enabled', 'urn:schemas-microsoft-com:unattend'))

                            $null = $autoLogonPasswordValueElement.AppendChild($unattendXml.CreateTextNode($AdminCredential.GetNetworkCredential().password))
                            $null = $autoLogonCountElement.AppendChild($unattendXml.CreateTextNode($LogonCount))
                            $null = $autoLogonUsernameElement.AppendChild($unattendXml.CreateTextNode('administrator'))
                            $null = $autoLogonEnabledElement.AppendChild($unattendXml.CreateTextNode('true'))
                        }

                        if (($Null -ne $FirstLogonExecuteCommand -or $FirstBootExecuteCommand.Length -gt 0) -and $component.'processorArchitecture' -eq 'x86') {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding First Logon Commands"
                            $commandOrder = 1
                            $FirstLogonCommandsElement = $component.AppendChild($unattendXml.CreateElement('FirstLogonCommands', 'urn:schemas-microsoft-com:unattend'))
                            foreach ($command in ($FirstLogonExecuteCommand | Sort-Object -Property {
                                        $_.order
                                    })) {
                                $CommandElement = $FirstLogonCommandsElement.AppendChild($unattendXml.CreateElement('SynchronousCommand', 'urn:schemas-microsoft-com:unattend'))
                                $CommandDescriptionElement = $CommandElement.AppendChild($unattendXml.CreateElement('Description', 'urn:schemas-microsoft-com:unattend'))
                                $CommandOrderElement = $CommandElement.AppendChild($unattendXml.CreateElement('Order', 'urn:schemas-microsoft-com:unattend'))
                                $CommandCommandLineElement = $CommandElement.AppendChild($unattendXml.CreateElement('CommandLine', 'urn:schemas-microsoft-com:unattend'))
                                $CommandRequireInputlement = $CommandElement.AppendChild($unattendXml.CreateElement('RequiresUserInput', 'urn:schemas-microsoft-com:unattend'))

                                $null = $CommandElement.SetAttribute('action', 'http://schemas.microsoft.com/WMIConfig/2002/State', 'add')
                                $null = $CommandDescriptionElement.AppendChild($unattendXml.CreateTextNode($command['Description']))
                                $null = $CommandOrderElement.AppendChild($unattendXml.CreateTextNode($commandOrder))
                                $null = $CommandCommandLineElement.AppendChild($unattendXml.CreateTextNode($command['CommandLine']))
                                $null = $CommandRequireInputlement.AppendChild($unattendXml.CreateTextNode('false'))
                                $commandOrder++
                            }
                        }
                        if (($null -ne $EveryLogonExecuteCommand -or $FirstBootExecuteCommand.Length -gt 0) -and $component.'processorArchitecture' -eq 'x86') {
                            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Adding Every-Logon Commands"
                            $commandOrder = 1
                            $FirstLogonCommandsElement = $component.AppendChild($unattendXml.CreateElement('LogonCommands', 'urn:schemas-microsoft-com:unattend'))
                            foreach ($command in ($EveryLogonExecuteCommand | Sort-Object -Property {
                                        $_.order
                                    })) {
                                $CommandElement = $FirstLogonCommandsElement.AppendChild($unattendXml.CreateElement('AsynchronousCommand', 'urn:schemas-microsoft-com:unattend'))
                                $CommandDescriptionElement = $CommandElement.AppendChild($unattendXml.CreateElement('Description', 'urn:schemas-microsoft-com:unattend'))
                                $CommandOrderElement = $CommandElement.AppendChild($unattendXml.CreateElement('Order', 'urn:schemas-microsoft-com:unattend'))
                                $CommandCommandLineElement = $CommandElement.AppendChild($unattendXml.CreateElement('CommandLine', 'urn:schemas-microsoft-com:unattend'))
                                $CommandRequireInputlement = $CommandElement.AppendChild($unattendXml.CreateElement('RequiresUserInput', 'urn:schemas-microsoft-com:unattend'))

                                $null = $CommandElement.SetAttribute('action', 'http://schemas.microsoft.com/WMIConfig/2002/State', 'add')
                                $null = $CommandDescriptionElement.AppendChild($unattendXml.CreateTextNode($command['Description']))
                                $null = $CommandOrderElement.AppendChild($unattendXml.CreateTextNode($commandOrder))
                                $null = $CommandCommandLineElement.AppendChild($unattendXml.CreateTextNode($command['CommandLine']))
                                $null = $CommandRequireInputlement.AppendChild($unattendXml.CreateTextNode('false'))
                                $commandOrder++
                            }
                        }
                    }
                } #end foreach setting.Component
            } #end foreach unattendXml.Unattend.Settings

            Write-Verbose -Message "[$($MyInvocation.MyCommand)] Saving file"

            $unattendXml.Save($Path)
            Get-ChildItem $Path
            # }
            # catch
            # {
            # throw $_.Exception.Message
            # }
        }
    }
}


function Get-UnattendChunk {
    param
    (
        [string] $pass,
        [string] $component,
        [string] $arch,
        [xml] $unattend
    )

    # Helper function that returns one component chunk from the Unattend XML data structure
    return $unattend.unattend.settings |
    Where-Object -Property pass -EQ -Value $pass |
    Select-Object -ExpandProperty component |
    Where-Object -Property name -EQ -Value $component |
    Where-Object -Property processorArchitecture -EQ -Value $arch
}