Advertisement
Guest User

Convert-WindowsImage.ps1

a guest
Sep 16th, 2012
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2.     .NOTES
  3.         Copyright (c) Microsoft Corporation.  All rights reserved.
  4.  
  5.         Use of this sample source code is subject to the terms of the Microsoft
  6.         license agreement under which you licensed this sample source code. If
  7.         you did not accept the terms of the license agreement, you are not
  8.         authorized to use this sample source code. For the terms of the license,
  9.         please see the license agreement between you and Microsoft or, if applicable,
  10.         see the LICENSE.RTF on your install media or the root of your tools installation.
  11.         THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
  12.    
  13.     .SYNOPSIS
  14.         Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media.
  15.  
  16.     .DESCRIPTION
  17.         Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media.
  18.  
  19.     .PARAMETER SourcePath
  20.         The complete path to the WIM or ISO file that will be converted to a Virtual Hard Disk.
  21.         The ISO file must be valid Windows installation media to be recognized successfully.
  22.  
  23.     .PARAMETER VHDPath
  24.         The name and path of the Virtual Hard Disk to create.
  25.         Omitting this parameter will create the Virtual Hard Disk is the current directory, (or,
  26.         if specified by the -WorkingDirectory parameter, the working directory) and will automatically
  27.         name the file in the following format:
  28.  
  29.         <build>.<revision>.<architecture>.<branch>.<timestamp>_<skufamily>_<sku>_<language>.<extension>
  30.         i.e.:
  31.         8250.0.amd64chk.winmain_win8beta.120217-1520_client_professional_en-us.vhd(x)
  32.  
  33.     .PARAMETER WorkingDirectory
  34.         Specifies the directory where the VHD(X) file should be generated.  
  35.         If specified along with -VHDPath, the -WorkingDirectory value is ignored.
  36.         The default value is the current directory ($pwd).
  37.  
  38.     .PARAMETER SizeBytes
  39.         The size of the Virtual Hard Disk to create.
  40.         For fixed disks, the VHD(X) file will be allocated all of this space immediately.
  41.         For dynamic disks, this will be the maximum size that the VHD(X) can grow to.
  42.         The default value is 40GB.
  43.  
  44.     .PARAMETER VHDFormat
  45.         Specifies whether to create a VHD or VHDX formatted Virtual Hard Disk.
  46.         The default is VHD.
  47.  
  48.     .PARAMETER VHDType
  49.         Specifies whether to create a fixed (fully allocated) VHD(X) or a dynamic (sparse) VHD(X).
  50.         The default is dynamic.
  51.  
  52.     .PARAMETER UnattendPath
  53.         The complete path to an unattend.xml file that can be injected into the VHD(X).
  54.  
  55.     .PARAMETER Edition
  56.         The name or image index of the image to apply from the WIM.
  57.  
  58.     .PARAMETER Passthru
  59.         Specifies that the full path to the VHD(X) that is created should be
  60.         returned on the pipeline.
  61.  
  62.     .PARAMETER BCDBoot
  63.         By default, the version of BCDBOOT.EXE that is present in \Windows\System32
  64.         is used by Convert-WindowsImage.  If you need to specify an alternate version,
  65.         use this parameter to do so.
  66.  
  67.     .PARAMETER ShowUI
  68.         Specifies that the Graphical User Interface should be displayed.
  69.  
  70.     .PARAMETER EnableDebugger
  71.         Configures kernel debugging for the VHD(X) being created.
  72.         EnableDebugger takes a single argument which specifies the debugging transport to use.
  73.         Valid transports are: None, Serial, 1394, USB, Network, Local.
  74.  
  75.         Depending on the type of transport selected, additional configuration parameters will become
  76.         available.
  77.  
  78.         Serial:
  79.             -ComPort   - The COM port number to use while communicating with the debugger.
  80.                          The default value is 1 (indicating COM1).
  81.             -BaudRate  - The baud rate (in bps) to use while communicating with the debugger.
  82.                          The default value is 115200, valid values are:
  83.                          9600, 19200, 38400, 56700, 115200
  84.            
  85.         1394:
  86.             -Channel   - The 1394 channel used to communicate with the debugger.
  87.                          The default value is 10.
  88.  
  89.         USB:
  90.             -Target    - The target name used for USB debugging.
  91.                          The default value is "debugging".
  92.  
  93.         Network:
  94.             -IPAddress - The IP address of the debugging host computer.
  95.             -Port      - The port on which to connect to the debugging host.
  96.                          The default value is 50000, with a minimum value of 49152.
  97.             -Key       - The key used to encrypt the connection.  Only [0-9] and [a-z] are allowed.
  98.             -nodhcp    - Prevents the use of DHCP to obtain the target IP address.
  99.             -newkey    - Specifies that a new encryption key should be generated for the connection.
  100.    
  101.     .EXAMPLE
  102.         .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -WorkingDirectory D:\foo
  103.  
  104.         This command will create a 40GB dynamically expanding VHD in the D:\foo folder.
  105.         The VHD will be based on the Professional edition from D:\foo\install.wim,
  106.         and will be named automatically.
  107.  
  108.     .EXAMPLE
  109.         .\Convert-WindowsImage.ps1 -SourcePath D:\foo\Win7SP1.iso -Edition Ultimate -VHDPath D:\foo\Win7_Ultimate_SP1.vhd
  110.  
  111.         This command will parse the ISO file D:\foo\Win7SP1.iso and try to locate
  112.         \sources\install.wim.  If that file is found, it will be used to create a
  113.         dynamically-expanding 40GB VHD containing the Ultimate SKU, and will be
  114.         named D:\foo\Win7_Ultimate_SP1.vhd
  115.  
  116.     .EXAMPLE
  117.         .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -EnableDebugger Serial -ComPort 2 -BaudRate 38400
  118.  
  119.         This command will create a VHD from D:\foo\install.wim of the Professional SKU.
  120.         Serial debugging will be enabled in the VHD via COM2 at a baud rate of 38400bps.
  121.  
  122.     .OUTPUTS
  123.         System.IO.FileInfo
  124. #>
  125. #Requires -Version 3.0
  126. [CmdletBinding(DefaultParameterSetName="SRC")]
  127. param(
  128.     [Parameter(ParameterSetName="SRC", Mandatory=$true, ValueFromPipeline=$true)]
  129.     [Alias("WIM")]
  130.     [string]
  131.     [ValidateNotNullOrEmpty()]
  132.     [ValidateScript({ Test-Path $(Resolve-Path $_) })]
  133.     $SourcePath,
  134.  
  135.     [Parameter(ParameterSetName="SRC")]
  136.     [Alias("VHD")]
  137.     [string]
  138.     [ValidateNotNullOrEmpty()]
  139.     $VHDPath,
  140.  
  141.     [Parameter(ParameterSetName="SRC")]
  142.     [Alias("WorkDir")]
  143.     [string]
  144.     [ValidateNotNullOrEmpty()]
  145.     [ValidateScript({ Test-Path $_ })]
  146.     $WorkingDirectory = $pwd,
  147.  
  148.     [Parameter(ParameterSetName="SRC")]
  149.     [Alias("Size")]
  150.     [UInt64]
  151.     [ValidateNotNullOrEmpty()]
  152.     [ValidateRange(512MB, 64TB)]
  153.     $SizeBytes        = 40GB,
  154.  
  155.     [Parameter(ParameterSetName="SRC")]
  156.     [Alias("Format")]
  157.     [string]
  158.     [ValidateNotNullOrEmpty()]
  159.     [ValidateSet("VHD", "VHDX")]
  160.     $VHDFormat        = "VHD",
  161.  
  162.     [Parameter(ParameterSetName="SRC")]
  163.     [Alias("DiskType")]
  164.     [string]
  165.     [ValidateNotNullOrEmpty()]
  166.     [ValidateSet("Dynamic", "Fixed")]
  167.     $VHDType          = "Dynamic",
  168.  
  169.     [Parameter(ParameterSetName="SRC")]
  170.     [Alias("Unattend")]
  171.     [string]
  172.     [ValidateNotNullOrEmpty()]
  173.     [ValidateScript({ Test-Path $(Resolve-Path $_) })]
  174.     $UnattendPath,
  175.  
  176.     [Parameter(ParameterSetName="SRC")]
  177.     [Alias("SKU")]
  178.     [string]
  179.     [ValidateNotNullOrEmpty()]
  180.     $Edition,
  181.  
  182.     [Parameter(ParameterSetName="SRC")]
  183.     [Parameter(ParameterSetName="UI")]
  184.     [string]
  185.     $BCDBoot          = "bcdboot.exe",
  186.  
  187.     [Parameter(ParameterSetName="SRC")]
  188.     [Parameter(ParameterSetName="UI")]
  189.     [switch]
  190.     $Passthru,
  191.  
  192.     [Parameter(ParameterSetName="UI")]
  193.     [switch]
  194.     $ShowUI,
  195.  
  196.     [Parameter(ParameterSetName="SRC")]
  197.     [Parameter(ParameterSetName="UI")]
  198.     [string]
  199.     [ValidateNotNullOrEmpty()]
  200.     [ValidateSet("None", "Serial", "1394", "USB", "Local", "Network")]
  201.     $EnableDebugger = "None"
  202. )
  203.  
  204. # Begin Dynamic Parameters
  205. # Create the parameters for the various types of debugging.
  206. DynamicParam {
  207.  
  208.     # Set up the dynamic parameters.
  209.     # Dynamic parameters are only available if certain conditions are met, so they'll only show up
  210.     # as valid parameters when those conditions apply.  Here, the conditions are based on the value of
  211.     # the EnableDebugger parameter.  Depending on which of a set of values is the specified argument
  212.     # for EnableDebugger, different parameters will light up, as outlined below.
  213.    
  214.     $parameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
  215.  
  216.     switch ($EnableDebugger) {
  217.        
  218.         "Serial" {
  219.             #region ComPort
  220.        
  221.             $ComPortAttr                   = New-Object System.Management.Automation.ParameterAttribute
  222.             $ComPortAttr.ParameterSetName  = "__AllParameterSets"
  223.             $ComPortAttr.Mandatory         = $false
  224.  
  225.             $ComPortValidator              = New-Object System.Management.Automation.ValidateRangeAttribute(
  226.                                                 1,
  227.                                                 10   # Is that a good maximum?
  228.                                              )
  229.  
  230.             $ComPortNotNull                = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  231.  
  232.             $ComPortAttrCollection         = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  233.             $ComPortAttrCollection.Add($ComPortAttr)
  234.             $ComPortAttrCollection.Add($ComPortValidator)
  235.             $ComPortAttrCollection.Add($ComPortNotNull)
  236.        
  237.             $ComPort                       = New-Object System.Management.Automation.RuntimeDefinedParameter(
  238.                                                 "ComPort",
  239.                                                 [UInt16],
  240.                                                 $ComPortAttrCollection
  241.                                              )
  242.  
  243.             # By default, use COM1
  244.             $ComPort.Value                 = 1
  245.             $parameterDictionary.Add("ComPort", $ComPort)
  246.             #endregion ComPort
  247.  
  248.             #region BaudRate
  249.             $BaudRateAttr                  = New-Object System.Management.Automation.ParameterAttribute
  250.             $BaudRateAttr.ParameterSetName = "__AllParameterSets"
  251.             $BaudRateAttr.Mandatory        = $false
  252.  
  253.             $BaudRateValidator             = New-Object System.Management.Automation.ValidateSetAttribute(
  254.                                                 9600, 19200,38400, 57600, 115200
  255.                                              )
  256.  
  257.             $BaudRateNotNull               = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  258.  
  259.             $BaudRateAttrCollection        = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  260.             $BaudRateAttrCollection.Add($BaudRateAttr)
  261.             $BaudRateAttrCollection.Add($BaudRateValidator)
  262.             $BaudRateAttrCollection.Add($BaudRateNotNull)
  263.  
  264.             $BaudRate                      = New-Object System.Management.Automation.RuntimeDefinedParameter(
  265.                                                  "BaudRate",
  266.                                                  [UInt32],
  267.                                                  $BaudRateAttrCollection
  268.                                              )
  269.  
  270.             # By default, use 115,200.
  271.             $BaudRate.Value                = 115200
  272.             $parameterDictionary.Add("BaudRate", $BaudRate)
  273.             break
  274.             #endregion BaudRate
  275.  
  276.         }
  277.        
  278.         "1394" {
  279.             $ChannelAttr                   = New-Object System.Management.Automation.ParameterAttribute
  280.             $ChannelAttr.ParameterSetName  = "__AllParameterSets"
  281.             $ChannelAttr.Mandatory         = $false
  282.  
  283.             $ChannelValidator              = New-Object System.Management.Automation.ValidateRangeAttribute(
  284.                                                 0,
  285.                                                 62
  286.                                              )
  287.  
  288.             $ChannelNotNull                = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  289.  
  290.             $ChannelAttrCollection         = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  291.             $ChannelAttrCollection.Add($ChannelAttr)
  292.             $ChannelAttrCollection.Add($ChannelValidator)
  293.             $ChannelAttrCollection.Add($ChannelNotNull)
  294.  
  295.             $Channel                       = New-Object System.Management.Automation.RuntimeDefinedParameter(
  296.                                                  "Channel",
  297.                                                  [UInt16],
  298.                                                  $ChannelAttrCollection
  299.                                              )
  300.  
  301.             # By default, use channel 10
  302.             $Channel.Value                 = 10
  303.             $parameterDictionary.Add("Channel", $Channel)
  304.             break
  305.         }
  306.        
  307.         "USB" {
  308.             $TargetAttr                    = New-Object System.Management.Automation.ParameterAttribute
  309.             $TargetAttr.ParameterSetName   = "__AllParameterSets"
  310.             $TargetAttr.Mandatory          = $false
  311.  
  312.             $TargetNotNull                 = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  313.  
  314.             $TargetAttrCollection          = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  315.             $TargetAttrCollection.Add($TargetAttr)
  316.             $TargetAttrCollection.Add($TargetNotNull)
  317.  
  318.             $Target                        = New-Object System.Management.Automation.RuntimeDefinedParameter(
  319.                                                  "Target",
  320.                                                  [string],
  321.                                                  $TargetAttrCollection
  322.                                              )
  323.  
  324.             # By default, use target = "debugging"
  325.             $Target.Value                  = "Debugging"
  326.             $parameterDictionary.Add("Target", $Target)
  327.             break
  328.         }
  329.        
  330.         "Network" {
  331.             #region IP
  332.             $IpAttr                        = New-Object System.Management.Automation.ParameterAttribute
  333.             $IpAttr.ParameterSetName       = "__AllParameterSets"
  334.             $IpAttr.Mandatory              = $true
  335.  
  336.             $IpValidator                   = New-Object System.Management.Automation.ValidatePatternAttribute(
  337.                                                 "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
  338.                                              )
  339.             $IpNotNull                     = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  340.  
  341.             $IpAttrCollection              = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  342.             $IpAttrCollection.Add($IpAttr)
  343.             $IpAttrCollection.Add($IpValidator)
  344.             $IpAttrCollection.Add($IpNotNull)
  345.  
  346.             $IP                            = New-Object System.Management.Automation.RuntimeDefinedParameter(
  347.                                                  "IPAddress",
  348.                                                  [string],
  349.                                                  $IpAttrCollection
  350.                                              )
  351.  
  352.             # There's no good way to set a default value for this.
  353.             $parameterDictionary.Add("IPAddress", $IP)
  354.             #endregion IP
  355.  
  356.             #region Port
  357.             $PortAttr                      = New-Object System.Management.Automation.ParameterAttribute
  358.             $PortAttr.ParameterSetName     = "__AllParameterSets"
  359.             $PortAttr.Mandatory            = $false
  360.  
  361.             $PortValidator                 = New-Object System.Management.Automation.ValidateRangeAttribute(
  362.                                                 49152,
  363.                                                 50039
  364.                                              )
  365.  
  366.             $PortNotNull                   = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  367.  
  368.             $PortAttrCollection            = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  369.             $PortAttrCollection.Add($PortAttr)
  370.             $PortAttrCollection.Add($PortValidator)
  371.             $PortAttrCollection.Add($PortNotNull)
  372.  
  373.  
  374.             $Port                          = New-Object System.Management.Automation.RuntimeDefinedParameter(
  375.                                                  "Port",
  376.                                                  [UInt16],
  377.                                                  $PortAttrCollection
  378.                                              )
  379.  
  380.             # By default, use port 50000
  381.             $Port.Value                    = 50000
  382.             $parameterDictionary.Add("Port", $Port)
  383.             #endregion Port
  384.  
  385.             #region Key
  386.             $KeyAttr                       = New-Object System.Management.Automation.ParameterAttribute
  387.             $KeyAttr.ParameterSetName      = "__AllParameterSets"
  388.             $KeyAttr.Mandatory             = $true
  389.  
  390.             $KeyValidator                  = New-Object System.Management.Automation.ValidatePatternAttribute(
  391.                                                 "\b([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+)\b"
  392.                                              )
  393.  
  394.             $KeyNotNull                    = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute
  395.  
  396.             $KeyAttrCollection             = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  397.             $KeyAttrCollection.Add($KeyAttr)
  398.             $KeyAttrCollection.Add($KeyValidator)
  399.             $KeyAttrCollection.Add($KeyNotNull)
  400.  
  401.             $Key                           = New-Object System.Management.Automation.RuntimeDefinedParameter(
  402.                                                  "Key",
  403.                                                  [string],
  404.                                                  $KeyAttrCollection
  405.                                              )
  406.  
  407.             # Don't set a default key.
  408.             $parameterDictionary.Add("Key", $Key)
  409.             #endregion Key
  410.  
  411.             #region NoDHCP
  412.             $NoDHCPAttr                    = New-Object System.Management.Automation.ParameterAttribute
  413.             $NoDHCPAttr.ParameterSetName   = "__AllParameterSets"
  414.             $NoDHCPAttr.Mandatory          = $false
  415.  
  416.             $NoDHCPAttrCollection          = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  417.             $NoDHCPAttrCollection.Add($NoDHCPAttr)
  418.  
  419.             $NoDHCP                        = New-Object System.Management.Automation.RuntimeDefinedParameter(
  420.                                                  "NoDHCP",
  421.                                                  [switch],
  422.                                                  $NoDHCPAttrCollection
  423.                                              )
  424.  
  425.             $parameterDictionary.Add("NoDHCP", $NoDHCP)
  426.             #endregion NoDHCP
  427.  
  428.             #region NewKey
  429.             $NewKeyAttr                    = New-Object System.Management.Automation.ParameterAttribute
  430.             $NewKeyAttr.ParameterSetName   = "__AllParameterSets"
  431.             $NewKeyAttr.Mandatory          = $false
  432.  
  433.             $NewKeyAttrCollection          = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  434.             $NewKeyAttrCollection.Add($NewKeyAttr)
  435.  
  436.             $NewKey                        = New-Object System.Management.Automation.RuntimeDefinedParameter(
  437.                                                  "NewKey",
  438.                                                  [switch],
  439.                                                  $NewKeyAttrCollection
  440.                                              )
  441.  
  442.             # Don't set a default key.
  443.             $parameterDictionary.Add("NewKey", $NewKey)
  444.             break
  445.             #endregion NewKey
  446.  
  447.         }
  448.        
  449.         # There's nothing to do for local debugging.
  450.         # Synthetic debugging is not yet implemented.
  451.        
  452.         default {
  453.            break
  454.         }
  455.     }
  456.    
  457.     return $parameterDictionary  
  458. }
  459.  
  460. Begin {
  461.     ##########################################################################################
  462.     #                             Constants and Pseudo-Constants
  463.     ##########################################################################################
  464.     $PARTITION_STYLE_MBR    = 0x00000000                                   # The default value
  465.     $PARTITION_STYLE_GPT    = 0x00000001                                   # Just in case...
  466.  
  467.     # Version information that can be populated by timebuild.
  468.     $ScriptVersion = DATA {
  469.     ConvertFrom-StringData -StringData @"
  470.        Major     = 6
  471.        Minor     = 2
  472.        Build     = 8424
  473.        QFE       = 1
  474.        Branch    = fbl_core1_hyp_dev(mikekol)
  475.        Timestamp = 120517-1616
  476.        Flavor    = amd64fre
  477. "@
  478. }
  479.  
  480.     $vQuality               = "Release Preview"
  481.  
  482.     $myVersion              = "$($ScriptVersion.Major).$($ScriptVersion.Minor).$($ScriptVersion.Build).$($ScriptVersion.QFE).$($ScriptVersion.Flavor).$($ScriptVersion.Branch).$($ScriptVersion.Timestamp)"
  483.     $scriptName             = "Convert-WindowsImage"                       # Name of the script, obviously.
  484.     $sessionKey             = [Guid]::NewGuid().ToString()                 # Session key, used for keeping records unique between multiple runs.
  485.     $logFolder              = "$($env:Temp)\$($scriptName)\$($sessionKey)" # Log folder path.
  486.     $vhdMaxSize             = 2040GB                                       # Maximum size for VHD is ~2040GB.
  487.     $vhdxMaxSize            = 64TB                                         # Maximum size for VHDX is ~64TB.
  488.     $lowestSupportedVersion = New-Object Version "6.1"                     # The lowest supported *image* version; making sure we don't run against Vista/2k8.
  489.     $lowestSupportedBuild   = 8250                                         # The lowest supported *host* build.  Set to Win8 CP.
  490.     $transcripting          = $false
  491.  
  492.     # Since we use the VHDFormat in output, make it uppercase.
  493.     # We'll make it lowercase again when we use it as a file extension.
  494.     $VHDFormat              = $VHDFormat.ToUpper()
  495.     ##########################################################################################
  496.     #                                      Here Strings
  497.     ##########################################################################################
  498.  
  499.     # Text used for flag file embedded in VHD(X)
  500.     $flagText = @"
  501. This $VHDFormat was created by Convert-WindowsImage.ps1 $myVersion $vQuality
  502. on $([DateTime]::Now).
  503. "@
  504.  
  505.     # Banner text displayed during each run.
  506.     $header    = @"
  507.  
  508. Windows(R) Image to Virtual Hard Disk Converter for Windows(R) 8
  509. Copyright (C) Microsoft Corporation.  All rights reserved.
  510. Version $myVersion $vQuality
  511.  
  512. "@
  513.  
  514.     # Text used as the banner in the UI.
  515.     $uiHeader  = @"
  516. You can use the fields below to configure the VHD or VHDX that you want to create!
  517. "@
  518.  
  519.     $code      = @"
  520. using System;
  521. using System.Collections.Generic;
  522. using System.Collections.ObjectModel;
  523. using System.ComponentModel;
  524. using System.Globalization;
  525. using System.IO;
  526. using System.Linq;
  527. using System.Runtime.InteropServices;
  528. using System.Security;
  529. using System.Text;
  530. using System.Text.RegularExpressions;
  531. using System.Threading;
  532. using System.Xml.Linq;
  533. using System.Xml.XPath;
  534. using Microsoft.Win32.SafeHandles;
  535.  
  536. namespace WIM2VHD {
  537.  
  538.    /// <summary>
  539.    /// P/Invoke methods and associated enums, flags, and structs.
  540.    /// </summary>
  541.    public class
  542.    NativeMethods {
  543.  
  544.        #region Delegates and Callbacks
  545.        #region WIMGAPI
  546.  
  547.        ///<summary>
  548.        ///User-defined function used with the RegisterMessageCallback or UnregisterMessageCallback function.
  549.        ///</summary>
  550.        ///<param name="MessageId">Specifies the message being sent.</param>
  551.        ///<param name="wParam">Specifies additional message information. The contents of this parameter depend on the value of the
  552.        ///MessageId parameter.</param>
  553.        ///<param name="lParam">Specifies additional message information. The contents of this parameter depend on the value of the
  554.        ///MessageId parameter.</param>
  555.        ///<param name="UserData">Specifies the user-defined value passed to RegisterCallback.</param>
  556.        ///<returns>
  557.        ///To indicate success and to enable other subscribers to process the message return WIM_MSG_SUCCESS.
  558.        ///To prevent other subscribers from receiving the message, return WIM_MSG_DONE.
  559.        ///To cancel an image apply or capture, return WIM_MSG_ABORT_IMAGE when handling the WIM_MSG_PROCESS message.
  560.        ///</returns>
  561.        public delegate uint
  562.        WimMessageCallback(
  563.            uint   MessageId,
  564.            IntPtr wParam,
  565.            IntPtr lParam,
  566.            IntPtr UserData
  567.        );
  568.  
  569.        public static void
  570.        RegisterMessageCallback(
  571.            WimFileHandle hWim,
  572.            WimMessageCallback callback) {
  573.  
  574.            uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero);
  575.            int rc = Marshal.GetLastWin32Error();
  576.            if (0 != rc) {
  577.                // Throw an exception if something bad happened on the Win32 end.
  578.                throw
  579.                    new InvalidOperationException(
  580.                        string.Format(
  581.                            CultureInfo.CurrentCulture,
  582.                            "Unable to register message callback."
  583.                ));
  584.            }
  585.        }
  586.  
  587.        public static void
  588.        UnregisterMessageCallback(
  589.            WimFileHandle hWim,
  590.            WimMessageCallback registeredCallback) {
  591.  
  592.            bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback);
  593.            int rc = Marshal.GetLastWin32Error();
  594.            if (!status) {
  595.                throw
  596.                    new InvalidOperationException(
  597.                        string.Format(
  598.                            CultureInfo.CurrentCulture,
  599.                            "Unable to unregister message callback."
  600.                ));
  601.            }
  602.        }
  603.  
  604.        #endregion WIMGAPI
  605.        #endregion Delegates and Callbacks
  606.  
  607.        #region Constants
  608.  
  609.        #region VDiskInterop
  610.  
  611.        /// <summary>
  612.        /// The default depth in a VHD parent chain that this library will search through.
  613.        /// If you want to go more than one disk deep into the parent chain, provide a different value.
  614.        /// </summary>
  615.        public   const uint  OPEN_VIRTUAL_DISK_RW_DEFAULT_DEPTH   = 0x00000001;
  616.  
  617.        public   const uint  DEFAULT_BLOCK_SIZE                   = 0x00080000;
  618.        public   const uint  DISK_SECTOR_SIZE                     = 0x00000200;
  619.  
  620.        internal const uint  ERROR_VIRTDISK_NOT_VIRTUAL_DISK      = 0xC03A0015;
  621.        internal const uint  ERROR_NOT_FOUND                      = 0x00000490;
  622.        internal const uint  ERROR_IO_PENDING                     = 0x000003E5;
  623.        internal const uint  ERROR_INSUFFICIENT_BUFFER            = 0x0000007A;
  624.        internal const uint  ERROR_ERROR_DEV_NOT_EXIST            = 0x00000037;
  625.        internal const uint  ERROR_BAD_COMMAND                    = 0x00000016;
  626.        internal const uint  ERROR_SUCCESS                        = 0x00000000;
  627.  
  628.        public   const uint  GENERIC_READ                         = 0x80000000;
  629.        public   const uint  GENERIC_WRITE                        = 0x40000000;
  630.        public   const short FILE_ATTRIBUTE_NORMAL                = 0x00000080;
  631.        public   const uint  CREATE_NEW                           = 0x00000001;
  632.        public   const uint  CREATE_ALWAYS                        = 0x00000002;
  633.        public   const uint  OPEN_EXISTING                        = 0x00000003;
  634.        public   const short INVALID_HANDLE_VALUE                 = -1;
  635.  
  636.        internal static Guid VirtualStorageTypeVendorUnknown      = new Guid("00000000-0000-0000-0000-000000000000");
  637.        internal static Guid VirtualStorageTypeVendorMicrosoft    = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B");
  638.  
  639.        #endregion VDiskInterop
  640.  
  641.        #region WIMGAPI
  642.  
  643.        public   const uint  WIM_FLAG_VERIFY                      = 0x00000002;
  644.        public   const uint  WIM_FLAG_INDEX                       = 0x00000004;
  645.  
  646.        public   const uint  WM_APP                               = 0x00008000;
  647.  
  648.        #endregion WIMGAPI
  649.  
  650.        #endregion Constants
  651.  
  652.        #region Enums and Flags
  653.  
  654.        #region VDiskInterop
  655.  
  656.        /// <summary>
  657.        /// Indicates the version of the virtual disk to create.
  658.        /// </summary>
  659.        public enum CreateVirtualDiskVersion : int {
  660.            VersionUnspecified         = 0x00000000,
  661.            Version1                   = 0x00000001,
  662.            Version2                   = 0x00000002
  663.        }
  664.  
  665.        public enum OpenVirtualDiskVersion : int {
  666.            VersionUnspecified         = 0x00000000,
  667.            Version1                   = 0x00000001,
  668.            Version2                   = 0x00000002
  669.        }
  670.  
  671.        /// <summary>
  672.        /// Contains the version of the virtual hard disk (VHD) ATTACH_VIRTUAL_DISK_PARAMETERS structure to use in calls to VHD functions.
  673.        /// </summary>
  674.        public enum AttachVirtualDiskVersion : int {
  675.            VersionUnspecified         = 0x00000000,
  676.            Version1                   = 0x00000001,
  677.            Version2                   = 0x00000002
  678.        }
  679.  
  680.        public enum CompactVirtualDiskVersion : int {
  681.            VersionUnspecified         = 0x00000000,
  682.            Version1                   = 0x00000001
  683.        }
  684.  
  685.        /// <summary>
  686.        /// Contains the type and provider (vendor) of the virtual storage device.
  687.        /// </summary>
  688.        public enum VirtualStorageDeviceType : int {
  689.            /// <summary>
  690.            /// The storage type is unknown or not valid.
  691.            /// </summary>
  692.            Unknown                    = 0x00000000,
  693.            /// <summary>
  694.            /// For internal use only.  This type is not supported.
  695.            /// </summary>
  696.            ISO                        = 0x00000001,
  697.            /// <summary>
  698.            /// Virtual Hard Disk device type.
  699.            /// </summary>
  700.            VHD                        = 0x00000002,
  701.            /// <summary>
  702.            /// Virtual Hard Disk v2 device type.
  703.            /// </summary>
  704.            VHDX                       = 0x00000003
  705.        }
  706.  
  707.        /// <summary>
  708.        /// Contains virtual hard disk (VHD) open request flags.
  709.        /// </summary>
  710.        [Flags]
  711.        public enum OpenVirtualDiskFlags {
  712.            /// <summary>
  713.            /// No flags. Use system defaults.
  714.            /// </summary>
  715.            None                       = 0x00000000,
  716.            /// <summary>
  717.            /// Open the VHD file (backing store) without opening any differencing-chain parents. Used to correct broken parent links.
  718.            /// </summary>
  719.            NoParents                  = 0x00000001,
  720.            /// <summary>
  721.            /// Reserved.
  722.            /// </summary>
  723.            BlankFile                  = 0x00000002,
  724.            /// <summary>
  725.            /// Reserved.
  726.            /// </summary>
  727.            BootDrive                  = 0x00000004,
  728.        }
  729.  
  730.        /// <summary>
  731.        /// Contains the bit mask for specifying access rights to a virtual hard disk (VHD).
  732.        /// </summary>
  733.        [Flags]
  734.        public enum VirtualDiskAccessMask {
  735.            /// <summary>
  736.            /// Only Version2 of OpenVirtualDisk API accepts this parameter
  737.            /// </summary>
  738.            None                       = 0x00000000,
  739.            /// <summary>
  740.            /// Open the virtual disk for read-only attach access. The caller must have READ access to the virtual disk image file.
  741.            /// </summary>
  742.            /// <remarks>
  743.            /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either
  744.            /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail.
  745.            /// </remarks>
  746.            AttachReadOnly             = 0x00010000,
  747.            /// <summary>
  748.            /// Open the virtual disk for read-write attaching access. The caller must have (READ | WRITE) access to the virtual disk image file.
  749.            /// </summary>
  750.            /// <remarks>
  751.            /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either
  752.            /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail.
  753.            /// If the virtual disk is part of a differencing chain, the disk for this request cannot be less than the readWriteDepth specified
  754.            /// during the prior open request for that differencing chain.
  755.            /// </remarks>
  756.            AttachReadWrite            = 0x00020000,
  757.            /// <summary>
  758.            /// Open the virtual disk to allow detaching of an attached virtual disk. The caller must have
  759.            /// (FILE_READ_ATTRIBUTES | FILE_READ_DATA) access to the virtual disk image file.
  760.            /// </summary>
  761.            Detach                     = 0x00040000,
  762.            /// <summary>
  763.            /// Information retrieval access to the virtual disk. The caller must have READ access to the virtual disk image file.
  764.            /// </summary>
  765.            GetInfo                    = 0x00080000,
  766.            /// <summary>
  767.            /// Virtual disk creation access.
  768.            /// </summary>
  769.            Create                     = 0x00100000,
  770.            /// <summary>
  771.            /// Open the virtual disk to perform offline meta-operations. The caller must have (READ | WRITE) access to the virtual
  772.            /// disk image file, up to readWriteDepth if working with a differencing chain.
  773.            /// </summary>
  774.            /// <remarks>
  775.            /// If the virtual disk is part of a differencing chain, the backing store (host volume) is opened in RW exclusive mode up to readWriteDepth.
  776.            /// </remarks>
  777.            MetaOperations             = 0x00200000,
  778.            /// <summary>
  779.            /// Reserved.
  780.            /// </summary>
  781.            Read                       = 0x000D0000,
  782.            /// <summary>
  783.            /// Allows unrestricted access to the virtual disk. The caller must have unrestricted access rights to the virtual disk image file.
  784.            /// </summary>
  785.            All                        = 0x003F0000,
  786.            /// <summary>
  787.            /// Reserved.
  788.            /// </summary>
  789.            Writable                   = 0x00320000
  790.        }
  791.  
  792.        /// <summary>
  793.        /// Contains virtual hard disk (VHD) creation flags.
  794.        /// </summary>
  795.        [Flags]
  796.        public enum CreateVirtualDiskFlags {
  797.            /// <summary>
  798.            /// Contains virtual hard disk (VHD) creation flags.
  799.            /// </summary>
  800.            None                       = 0x00000000,
  801.            /// <summary>
  802.            /// Pre-allocate all physical space necessary for the size of the virtual disk.
  803.            /// </summary>
  804.            /// <remarks>
  805.            /// The CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION flag is used for the creation of a fixed VHD.
  806.            /// </remarks>
  807.            FullPhysicalAllocation     = 0x00000001
  808.        }
  809.  
  810.        /// <summary>
  811.        /// Contains virtual disk attach request flags.
  812.        /// </summary>
  813.        [Flags]
  814.        public enum AttachVirtualDiskFlags {
  815.            /// <summary>
  816.            /// No flags. Use system defaults.
  817.            /// </summary>
  818.            None                       = 0x00000000,
  819.            /// <summary>
  820.            /// Attach the virtual disk as read-only.
  821.            /// </summary>
  822.            ReadOnly                   = 0x00000001,
  823.            /// <summary>
  824.            /// No drive letters are assigned to the disk's volumes.
  825.            /// </summary>
  826.            /// <remarks>Oddly enough, this doesn't apply to NTFS mount points.</remarks>
  827.            NoDriveLetter              = 0x00000002,
  828.            /// <summary>
  829.            /// Will decouple the virtual disk lifetime from that of the VirtualDiskHandle.
  830.            /// The virtual disk will be attached until the Detach() function is called, even if all open handles to the virtual disk are closed.
  831.            /// </summary>
  832.            PermanentLifetime          = 0x00000004,
  833.            /// <summary>
  834.            /// Reserved.
  835.            /// </summary>
  836.            NoLocalHost                = 0x00000008
  837.        }
  838.  
  839.        [Flags]
  840.        public enum DetachVirtualDiskFlag {
  841.            None                       = 0x00000000
  842.        }
  843.  
  844.        [Flags]
  845.        public enum CompactVirtualDiskFlags {
  846.            None                       = 0x00000000,
  847.            NoZeroScan                 = 0x00000001,
  848.            NoBlockMoves               = 0x00000002
  849.        }
  850.  
  851.        #endregion VDiskInterop
  852.  
  853.        #region WIMGAPI
  854.  
  855.        [FlagsAttribute]
  856.        internal enum
  857.        WimCreateFileDesiredAccess
  858.            : uint {
  859.            WimQuery                   = 0x00000000,
  860.            WimGenericRead             = 0x80000000
  861.        }
  862.  
  863.        /// <summary>
  864.        /// Specifies how the file is to be treated and what features are to be used.
  865.        /// </summary>
  866.        [FlagsAttribute]
  867.        internal enum
  868.        WimApplyFlags
  869.            : uint {
  870.            /// <summary>
  871.            /// No flags.
  872.            /// </summary>
  873.            WimApplyFlagsNone          = 0x00000000,
  874.            /// <summary>
  875.            /// Reserved.
  876.            /// </summary>
  877.            WimApplyFlagsReserved      = 0x00000001,
  878.            /// <summary>
  879.            /// Verifies that files match original data.
  880.            /// </summary>
  881.            WimApplyFlagsVerify        = 0x00000002,
  882.            /// <summary>
  883.            /// Specifies that the image is to be sequentially read for caching or performance purposes.
  884.            /// </summary>
  885.            WimApplyFlagsIndex         = 0x00000004,
  886.            /// <summary>
  887.            /// Applies the image without physically creating directories or files. Useful for obtaining a list of files and directories in the image.
  888.            /// </summary>
  889.            WimApplyFlagsNoApply       = 0x00000008,
  890.            /// <summary>
  891.            /// Disables restoring security information for directories.
  892.            /// </summary>
  893.            WimApplyFlagsNoDirAcl      = 0x00000010,
  894.            /// <summary>
  895.            /// Disables restoring security information for files
  896.            /// </summary>
  897.            WimApplyFlagsNoFileAcl     = 0x00000020,
  898.            /// <summary>
  899.            /// The .wim file is opened in a mode that enables simultaneous reading and writing.
  900.            /// </summary>
  901.            WimApplyFlagsShareWrite    = 0x00000040,
  902.            /// <summary>
  903.            /// Sends a WIM_MSG_FILEINFO message during the apply operation.
  904.            /// </summary>
  905.            WimApplyFlagsFileInfo      = 0x00000080,
  906.            /// <summary>
  907.            /// Disables automatic path fixups for junctions and symbolic links.
  908.            /// </summary>
  909.            WimApplyFlagsNoRpFix       = 0x00000100,
  910.            /// <summary>
  911.            /// Returns a handle that cannot commit changes, regardless of the access level requested at mount time.
  912.            /// </summary>
  913.            WimApplyFlagsMountReadOnly = 0x00000200,
  914.            /// <summary>
  915.            /// Reserved.
  916.            /// </summary>
  917.            WimApplyFlagsMountFast     = 0x00000400,
  918.            /// <summary>
  919.            /// Reserved.
  920.            /// </summary>
  921.            WimApplyFlagsMountLegacy   = 0x00000800
  922.        }
  923.  
  924.        public enum WimMessage : uint {
  925.            WIM_MSG                    = WM_APP + 0x1476,                
  926.            WIM_MSG_TEXT,
  927.            ///<summary>
  928.            ///Indicates an update in the progress of an image application.
  929.            ///</summary>
  930.            WIM_MSG_PROGRESS,
  931.            ///<summary>
  932.            ///Enables the caller to prevent a file or a directory from being captured or applied.
  933.            ///</summary>
  934.            WIM_MSG_PROCESS,
  935.            ///<summary>
  936.            ///Indicates that volume information is being gathered during an image capture.
  937.            ///</summary>
  938.            WIM_MSG_SCANNING,
  939.            ///<summary>
  940.            ///Indicates the number of files that will be captured or applied.
  941.            ///</summary>
  942.            WIM_MSG_SETRANGE,
  943.            ///<summary>
  944.            ///Indicates the number of files that have been captured or applied.
  945.            ///</summary>
  946.            WIM_MSG_SETPOS,
  947.            ///<summary>
  948.            ///Indicates that a file has been either captured or applied.
  949.            ///</summary>
  950.            WIM_MSG_STEPIT,
  951.            ///<summary>
  952.            ///Enables the caller to prevent a file resource from being compressed during a capture.
  953.            ///</summary>
  954.            WIM_MSG_COMPRESS,
  955.            ///<summary>
  956.            ///Alerts the caller that an error has occurred while capturing or applying an image.
  957.            ///</summary>
  958.            WIM_MSG_ERROR,
  959.            ///<summary>
  960.            ///Enables the caller to align a file resource on a particular alignment boundary.
  961.            ///</summary>
  962.            WIM_MSG_ALIGNMENT,
  963.            WIM_MSG_RETRY,
  964.            ///<summary>
  965.            ///Enables the caller to align a file resource on a particular alignment boundary.
  966.            ///</summary>
  967.            WIM_MSG_SPLIT,
  968.            WIM_MSG_SUCCESS            = 0x00000000,                
  969.            WIM_MSG_ABORT_IMAGE        = 0xFFFFFFFF
  970.        }
  971.  
  972.        internal enum
  973.        WimCreationDisposition
  974.            : uint {
  975.            WimOpenExisting            = 0x00000003,
  976.        }
  977.  
  978.        internal enum
  979.        WimActionFlags
  980.            : uint {
  981.            WimIgnored                 = 0x00000000
  982.        }
  983.  
  984.        internal enum
  985.        WimCompressionType
  986.            : uint {
  987.            WimIgnored                 = 0x00000000
  988.        }
  989.  
  990.        internal enum
  991.        WimCreationResult
  992.            : uint {
  993.            WimCreatedNew              = 0x00000000,
  994.            WimOpenedExisting          = 0x00000001
  995.        }
  996.  
  997.        #endregion WIMGAPI
  998.  
  999.        #endregion Enums and Flags
  1000.  
  1001.        #region Structs
  1002.  
  1003.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1004.        public struct CreateVirtualDiskParameters {
  1005.            /// <summary>
  1006.            /// 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.
  1007.            /// </summary>
  1008.            public CreateVirtualDiskVersion Version;
  1009.  
  1010.            /// <summary>
  1011.            /// Unique identifier to assign to the virtual disk object. If this member is set to zero, a unique identifier is created by the system.
  1012.            /// </summary>
  1013.            public Guid UniqueId;
  1014.  
  1015.            /// <summary>
  1016.            /// The maximum virtual size of the virtual disk object. Must be a multiple of 512.
  1017.            /// If a ParentPath is specified, this value must be zero.
  1018.            /// 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.
  1019.            /// </summary>
  1020.            public ulong MaximumSize;
  1021.  
  1022.            /// <summary>
  1023.            /// Internal size of the virtual disk object blocks.
  1024.            /// The following are predefined block sizes and their behaviors. For a fixed VHD type, this parameter must be zero.
  1025.            /// </summary>
  1026.            public uint BlockSizeInBytes;
  1027.  
  1028.            /// <summary>
  1029.            /// Internal size of the virtual disk object sectors. Must be set to 512.
  1030.            /// </summary>
  1031.            public uint SectorSizeInBytes;
  1032.  
  1033.            /// <summary>
  1034.            /// Optional path to a parent virtual disk object. Associates the new virtual disk with an existing virtual disk.
  1035.            /// If this parameter is not NULL, SourcePath must be NULL.
  1036.            /// </summary>
  1037.            public string ParentPath;
  1038.  
  1039.            /// <summary>
  1040.            /// 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.
  1041.            /// If this parameter is not NULL, ParentPath must be NULL.
  1042.            /// </summary>
  1043.            public string SourcePath;
  1044.  
  1045.            /// <summary>
  1046.            /// Flags for opening the VHD
  1047.            /// </summary>
  1048.            public OpenVirtualDiskFlags OpenFlags;
  1049.  
  1050.            /// <summary>
  1051.            /// GetInfoOnly flag for V2 handles
  1052.            /// </summary>
  1053.            public bool GetInfoOnly;
  1054.  
  1055.            /// <summary>
  1056.            /// Virtual Storage Type of the parent disk
  1057.            /// </summary>
  1058.            public VirtualStorageType ParentVirtualStorageType;
  1059.  
  1060.            /// <summary>
  1061.            /// Virtual Storage Type of the source disk
  1062.            /// </summary>
  1063.            public VirtualStorageType SourceVirtualStorageType;
  1064.  
  1065.            /// <summary>
  1066.            /// A GUID to use for fallback resiliency over SMB.
  1067.            /// </summary>
  1068.            public Guid ResiliencyGuid;
  1069.        }
  1070.  
  1071.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1072.        public struct VirtualStorageType {
  1073.            public VirtualStorageDeviceType DeviceId;
  1074.            public Guid VendorId;
  1075.        }
  1076.  
  1077.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1078.        public struct SecurityDescriptor {
  1079.            public byte revision;
  1080.            public byte size;
  1081.            public short control;
  1082.            public IntPtr owner;
  1083.            public IntPtr group;
  1084.            public IntPtr sacl;
  1085.            public IntPtr dacl;
  1086.        }
  1087.  
  1088.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1089.        public struct
  1090.        OpenVirtualDiskParameters {
  1091.            public OpenVirtualDiskVersion Version;
  1092.            public bool GetInfoOnly;
  1093.            public Guid ResiliencyGuid;
  1094.        }
  1095.  
  1096.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1097.        public struct VirtualDiskProgress {
  1098.            public int OperationStatus;
  1099.            public ulong CurrentValue;
  1100.            public ulong CompletionValue;
  1101.        }
  1102.  
  1103.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1104.        public struct AttachVirtualDiskParameters {
  1105.            public AttachVirtualDiskVersion Version;
  1106.            public int Reserved;
  1107.        }
  1108.  
  1109.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  1110.        public struct CompactVirtualDiskParameters {
  1111.            public CompactVirtualDiskVersion Version;
  1112.            public uint Reserved;
  1113.        }
  1114.  
  1115.        #endregion Structs
  1116.  
  1117.        #region VirtDisk.DLL P/Invoke
  1118.  
  1119.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1120.        public static extern uint
  1121.        CreateVirtualDisk(
  1122.            [In, Out] ref VirtualStorageType VirtualStorageType,
  1123.            [In]          string Path,
  1124.            [In]          VirtualDiskAccessMask VirtualDiskAccessMask,
  1125.            [In, Out] ref SecurityDescriptor SecurityDescriptor,
  1126.            [In]          CreateVirtualDiskFlags Flags,
  1127.            [In]          uint ProviderSpecificFlags,
  1128.            [In, Out] ref CreateVirtualDiskParameters Parameters,
  1129.            [In]          IntPtr Overlapped,
  1130.            [Out]     out SafeFileHandle Handle);
  1131.  
  1132.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1133.        internal static extern uint
  1134.        OpenVirtualDisk(
  1135.            [In, Out] ref VirtualStorageType VirtualStorageType,
  1136.            [In]          string Path,
  1137.            [In]          VirtualDiskAccessMask VirtualDiskAccessMask,
  1138.            [In]          OpenVirtualDiskFlags Flags,
  1139.            [In, Out] ref OpenVirtualDiskParameters Parameters,
  1140.            [Out]     out SafeFileHandle Handle);
  1141.  
  1142.        /// <summary>
  1143.        /// GetVirtualDiskOperationProgress API allows getting progress info for the async virtual disk operations (ie. Online Mirror)
  1144.        /// </summary>
  1145.        /// <param name="VirtualDiskHandle"></param>
  1146.        /// <param name="Overlapped"></param>
  1147.        /// <param name="Progress"></param>
  1148.        /// <returns></returns>
  1149.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1150.        internal static extern uint
  1151.        GetVirtualDiskOperationProgress(
  1152.            [In]          SafeFileHandle VirtualDiskHandle,
  1153.            [In]          IntPtr Overlapped,
  1154.            [In, Out] ref VirtualDiskProgress Progress);
  1155.  
  1156.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1157.        public static extern uint
  1158.        AttachVirtualDisk(
  1159.            [In]          SafeFileHandle VirtualDiskHandle,
  1160.            [In, Out] ref SecurityDescriptor SecurityDescriptor,
  1161.            [In]          AttachVirtualDiskFlags Flags,
  1162.            [In]          uint ProviderSpecificFlags,
  1163.            [In, Out] ref AttachVirtualDiskParameters Parameters,
  1164.            [In]          IntPtr Overlapped);
  1165.  
  1166.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1167.        public static extern uint
  1168.        DetachVirtualDisk(
  1169.            [In]          SafeFileHandle VirtualDiskHandle,
  1170.            [In]          NativeMethods.DetachVirtualDiskFlag Flags,
  1171.            [In]          uint ProviderSpecificFlags);
  1172.  
  1173.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1174.        public static extern uint
  1175.        CompactVirtualDisk(
  1176.            [In]          SafeFileHandle VirtualDiskHandle,
  1177.            [In]          CompactVirtualDiskFlags Flags,
  1178.            [In, Out] ref CompactVirtualDiskParameters Parameters,
  1179.            [In]          IntPtr Overlapped);
  1180.  
  1181.        [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)]
  1182.        public static extern uint
  1183.        GetVirtualDiskPhysicalPath(
  1184.            [In]          SafeFileHandle VirtualDiskHandle,
  1185.            [In, Out] ref uint DiskPathSizeInBytes,
  1186.            [Out]         StringBuilder DiskPath);
  1187.  
  1188.        #endregion VirtDisk.DLL P/Invoke
  1189.  
  1190.        #region Win32 P/Invoke
  1191.  
  1192.        [DllImport("advapi32", SetLastError = true)]
  1193.        public static extern bool InitializeSecurityDescriptor(
  1194.            [Out]     out SecurityDescriptor pSecurityDescriptor,
  1195.            [In]          uint dwRevision);
  1196.  
  1197.        /// <summary>
  1198.        /// CreateEvent API is used while calling async Online Mirror API
  1199.        /// </summary>
  1200.        /// <param name="lpEventAttributes"></param>
  1201.        /// <param name="bManualReset"></param>
  1202.        /// <param name="bInitialState"></param>
  1203.        /// <param name="lpName"></param>
  1204.        /// <returns></returns>
  1205.        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
  1206.        internal static extern IntPtr
  1207.        CreateEvent(
  1208.            [In, Optional]  IntPtr lpEventAttributes,
  1209.            [In]            bool bManualReset,
  1210.            [In]            bool bInitialState,
  1211.            [In, Optional]  string lpName);
  1212.  
  1213.        #endregion Win32 P/Invoke
  1214.  
  1215.        #region WIMGAPI P/Invoke
  1216.  
  1217.        #region SafeHandle wrappers for WimFileHandle and WimImageHandle
  1218.  
  1219.        public sealed class WimFileHandle : SafeHandle {
  1220.  
  1221.            public WimFileHandle(
  1222.                string wimPath)
  1223.                : base(IntPtr.Zero, true) {
  1224.  
  1225.                if (String.IsNullOrEmpty(wimPath)) {
  1226.                    throw new ArgumentNullException("wimPath");
  1227.                }
  1228.  
  1229.                if (!File.Exists(Path.GetFullPath(wimPath))) {
  1230.                    throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
  1231.                }
  1232.  
  1233.                NativeMethods.WimCreationResult creationResult;
  1234.  
  1235.                this.handle = NativeMethods.WimCreateFile(
  1236.                    wimPath,
  1237.                    NativeMethods.WimCreateFileDesiredAccess.WimGenericRead,
  1238.                    NativeMethods.WimCreationDisposition.WimOpenExisting,
  1239.                    NativeMethods.WimActionFlags.WimIgnored,
  1240.                    NativeMethods.WimCompressionType.WimIgnored,
  1241.                    out creationResult
  1242.                );
  1243.  
  1244.                // Check results.
  1245.                if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting) {
  1246.                    throw new Win32Exception();
  1247.                }
  1248.  
  1249.                if (this.handle == IntPtr.Zero) {
  1250.                    throw new Win32Exception();
  1251.                }
  1252.  
  1253.                // Set the temporary path.
  1254.                NativeMethods.WimSetTemporaryPath(
  1255.                    this,
  1256.                    Environment.ExpandEnvironmentVariables("%TEMP%")
  1257.                );
  1258.            }
  1259.  
  1260.            protected override bool ReleaseHandle() {
  1261.                return NativeMethods.WimCloseHandle(this.handle);
  1262.            }
  1263.  
  1264.            public override bool IsInvalid {
  1265.                get { return this.handle == IntPtr.Zero; }
  1266.            }
  1267.        }
  1268.  
  1269.        public sealed class WimImageHandle : SafeHandle {
  1270.            public WimImageHandle(
  1271.                WimFile Container,
  1272.                uint ImageIndex)
  1273.                : base(IntPtr.Zero, true) {
  1274.  
  1275.                if (null == Container) {
  1276.                    throw new ArgumentNullException("Container");
  1277.                }
  1278.  
  1279.                if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
  1280.                    throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
  1281.                }
  1282.  
  1283.                if (ImageIndex > Container.ImageCount) {
  1284.                    throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
  1285.                }
  1286.  
  1287.                this.handle = NativeMethods.WimLoadImage(
  1288.                    Container.Handle.DangerousGetHandle(),
  1289.                    ImageIndex);
  1290.            }
  1291.  
  1292.            protected override bool ReleaseHandle() {
  1293.                return NativeMethods.WimCloseHandle(this.handle);
  1294.            }
  1295.  
  1296.            public override bool IsInvalid {
  1297.                get { return this.handle == IntPtr.Zero; }
  1298.            }
  1299.        }
  1300.  
  1301.        #endregion SafeHandle wrappers for WimFileHandle and WimImageHandle
  1302.  
  1303.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")]
  1304.        internal static extern IntPtr
  1305.        WimCreateFile(
  1306.            [In, MarshalAs(UnmanagedType.LPWStr)] string WimPath,
  1307.            [In]    WimCreateFileDesiredAccess DesiredAccess,
  1308.            [In]    WimCreationDisposition CreationDisposition,
  1309.            [In]    WimActionFlags FlagsAndAttributes,
  1310.            [In]    WimCompressionType CompressionType,
  1311.            [Out, Optional] out WimCreationResult CreationResult
  1312.        );
  1313.  
  1314.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")]
  1315.        [return: MarshalAs(UnmanagedType.Bool)]
  1316.        internal static extern bool
  1317.        WimCloseHandle(
  1318.            [In]    IntPtr Handle
  1319.        );
  1320.  
  1321.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")]
  1322.        internal static extern IntPtr
  1323.        WimLoadImage(
  1324.            [In]    IntPtr Handle,
  1325.            [In]    uint ImageIndex
  1326.        );
  1327.  
  1328.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")]
  1329.        internal static extern uint
  1330.        WimGetImageCount(
  1331.            [In]    WimFileHandle Handle
  1332.        );
  1333.  
  1334.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMApplyImage")]
  1335.        internal static extern bool
  1336.        WimApplyImage(
  1337.            [In]    WimImageHandle Handle,
  1338.            [In, Optional, MarshalAs(UnmanagedType.LPWStr)] string Path,
  1339.            [In]    WimApplyFlags Flags
  1340.        );
  1341.  
  1342.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")]
  1343.        [return: MarshalAs(UnmanagedType.Bool)]
  1344.        internal static extern bool
  1345.        WimGetImageInformation(
  1346.            [In]        SafeHandle Handle,
  1347.            [Out]   out StringBuilder ImageInfo,
  1348.            [Out]   out uint SizeOfImageInfo
  1349.        );
  1350.  
  1351.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")]
  1352.        [return: MarshalAs(UnmanagedType.Bool)]
  1353.        internal static extern bool
  1354.        WimSetTemporaryPath(
  1355.            [In]    WimFileHandle Handle,
  1356.            [In]    string TempPath
  1357.        );
  1358.  
  1359.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
  1360.        internal static extern uint
  1361.        WimRegisterMessageCallback(
  1362.            [In, Optional] WimFileHandle      hWim,
  1363.            [In]           WimMessageCallback MessageProc,
  1364.            [In, Optional] IntPtr             ImageInfo
  1365.        );
  1366.  
  1367.        [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)]
  1368.        [return: MarshalAs(UnmanagedType.Bool)]
  1369.        internal static extern bool
  1370.        WimUnregisterMessageCallback(
  1371.            [In, Optional] WimFileHandle      hWim,
  1372.            [In]           WimMessageCallback MessageProc
  1373.        );
  1374.  
  1375.  
  1376.        #endregion WIMGAPI P/Invoke
  1377.    }
  1378.  
  1379.    #region WIM Interop
  1380.  
  1381.    public class WimFile {
  1382.  
  1383.        internal XDocument m_xmlInfo;
  1384.        internal List<WimImage> m_imageList;
  1385.  
  1386.        private static NativeMethods.WimMessageCallback wimMessageCallback;
  1387.        
  1388.        #region Events
  1389.        
  1390.        /// <summary>
  1391.        /// DefaultImageEvent handler
  1392.        /// </summary>
  1393.        public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e);
  1394.  
  1395.        ///<summary>
  1396.        ///ProcessFileEvent handler
  1397.        ///</summary>
  1398.        public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e);
  1399.                
  1400.        ///<summary>
  1401.        ///Enable the caller to prevent a file resource from being compressed during a capture.
  1402.        ///</summary>
  1403.        public event ProcessFileEventHandler ProcessFileEvent;
  1404.  
  1405.        ///<summary>
  1406.        ///Indicate an update in the progress of an image application.
  1407.        ///</summary>
  1408.        public event DefaultImageEventHandler ProgressEvent;
  1409.  
  1410.        ///<summary>
  1411.        ///Alert the caller that an error has occurred while capturing or applying an image.
  1412.        ///</summary>
  1413.        public event DefaultImageEventHandler ErrorEvent;
  1414.  
  1415.        ///<summary>
  1416.        ///Indicate that a file has been either captured or applied.
  1417.        ///</summary>
  1418.        public event DefaultImageEventHandler StepItEvent;
  1419.  
  1420.        ///<summary>
  1421.        ///Indicate the number of files that will be captured or applied.
  1422.        ///</summary>
  1423.        public event DefaultImageEventHandler SetRangeEvent;
  1424.  
  1425.        ///<summary>
  1426.        ///Indicate the number of files that have been captured or applied.
  1427.        ///</summary>
  1428.        public event DefaultImageEventHandler SetPosEvent;
  1429.  
  1430.        #endregion Events
  1431.  
  1432.        private
  1433.        enum
  1434.        ImageEventMessage : uint {
  1435.            ///<summary>
  1436.            ///Enables the caller to prevent a file or a directory from being captured or applied.
  1437.            ///</summary>
  1438.            Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS,
  1439.            ///<summary>
  1440.            ///Notification sent to enable the caller to prevent a file or a directory from being captured or applied.
  1441.            ///To prevent a file or a directory from being captured or applied, call WindowsImageContainer.SkipFile().
  1442.            ///</summary>
  1443.            Process = NativeMethods.WimMessage.WIM_MSG_PROCESS,
  1444.            ///<summary>
  1445.            ///Enables the caller to prevent a file resource from being compressed during a capture.
  1446.            ///</summary>
  1447.            Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS,
  1448.            ///<summary>
  1449.            ///Alerts the caller that an error has occurred while capturing or applying an image.
  1450.            ///</summary>
  1451.            Error = NativeMethods.WimMessage.WIM_MSG_ERROR,
  1452.            ///<summary>
  1453.            ///Enables the caller to align a file resource on a particular alignment boundary.
  1454.            ///</summary>
  1455.            Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT,
  1456.            ///<summary>
  1457.            ///Enables the caller to align a file resource on a particular alignment boundary.
  1458.            ///</summary>
  1459.            Split = NativeMethods.WimMessage.WIM_MSG_SPLIT,
  1460.            ///<summary>
  1461.            ///Indicates that volume information is being gathered during an image capture.
  1462.            ///</summary>
  1463.            Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING,
  1464.            ///<summary>
  1465.            ///Indicates the number of files that will be captured or applied.
  1466.            ///</summary>
  1467.            SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE,
  1468.            ///<summary>
  1469.            ///Indicates the number of files that have been captured or applied.
  1470.            /// </summary>
  1471.            SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS,
  1472.            ///<summary>
  1473.            ///Indicates that a file has been either captured or applied.
  1474.            ///</summary>
  1475.            StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT,
  1476.            ///<summary>
  1477.            ///Success.
  1478.            ///</summary>
  1479.            Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS,
  1480.            ///<summary>
  1481.            ///Abort.
  1482.            ///</summary>
  1483.            Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE
  1484.        }
  1485.  
  1486.        ///<summary>
  1487.        ///Event callback to the Wimgapi events
  1488.        ///</summary>
  1489.        private        
  1490.        uint
  1491.        ImageEventMessagePump(
  1492.            uint MessageId,
  1493.            IntPtr wParam,
  1494.            IntPtr lParam,
  1495.            IntPtr UserData) {
  1496.  
  1497.            uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS;
  1498.  
  1499.            DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData);
  1500.  
  1501.            switch ((ImageEventMessage)MessageId) {
  1502.  
  1503.                case ImageEventMessage.Progress:
  1504.                    ProgressEvent(this, eventArgs);
  1505.                    break;
  1506.  
  1507.                case ImageEventMessage.Process:
  1508.                    if (null != ProcessFileEvent) {
  1509.                        string fileToImage = Marshal.PtrToStringUni(wParam);
  1510.                        ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam);
  1511.                        ProcessFileEvent(this, fileToProcess);
  1512.  
  1513.                        if (fileToProcess.Abort == true) {
  1514.                            status = (uint)ImageEventMessage.Abort;
  1515.                        }
  1516.                    }
  1517.                    break;
  1518.  
  1519.                case ImageEventMessage.Error:
  1520.                    if (null != ErrorEvent) {
  1521.                        ErrorEvent(this, eventArgs);
  1522.                    }
  1523.                    break;
  1524.                    
  1525.                case ImageEventMessage.SetRange:
  1526.                    if (null != SetRangeEvent) {
  1527.                        SetRangeEvent(this, eventArgs);
  1528.                    }
  1529.                    break;
  1530.  
  1531.                case ImageEventMessage.SetPos:
  1532.                    if (null != SetPosEvent) {
  1533.                        SetPosEvent(this, eventArgs);
  1534.                    }
  1535.                    break;
  1536.  
  1537.                case ImageEventMessage.StepIt:
  1538.                    if (null != StepItEvent) {
  1539.                        StepItEvent(this, eventArgs);
  1540.                    }
  1541.                    break;
  1542.  
  1543.                default:
  1544.                    break;
  1545.            }
  1546.            return status;
  1547.            
  1548.        }
  1549.  
  1550.        /// <summary>
  1551.        /// Constructor.
  1552.        /// </summary>
  1553.        /// <param name="wimPath">Path to the WIM container.</param>
  1554.        public
  1555.        WimFile(string wimPath) {
  1556.            if (string.IsNullOrEmpty(wimPath)) {
  1557.                throw new ArgumentNullException("wimPath");
  1558.            }
  1559.  
  1560.            if (!File.Exists(Path.GetFullPath(wimPath))) {
  1561.                throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath);
  1562.            }
  1563.  
  1564.            Handle = new NativeMethods.WimFileHandle(wimPath);
  1565.  
  1566.            // Hook up the events before we return.
  1567.            //wimMessageCallback = new NativeMethods.WimMessageCallback(ImageEventMessagePump);
  1568.            //NativeMethods.RegisterMessageCallback(this.Handle, wimMessageCallback);
  1569.        }
  1570.  
  1571.        /// <summary>
  1572.        /// Closes the WIM file.
  1573.        /// </summary>
  1574.        public void
  1575.        Close() {
  1576.            foreach (WimImage image in Images) {
  1577.                image.Close();
  1578.            }
  1579.  
  1580.            if (null != wimMessageCallback) {
  1581.                NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback);
  1582.                wimMessageCallback = null;
  1583.            }
  1584.  
  1585.            if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
  1586.                Handle.Close();
  1587.            }
  1588.        }
  1589.  
  1590.        /// <summary>
  1591.        /// Provides a list of WimImage objects, representing the images in the WIM container file.
  1592.        /// </summary>
  1593.        public List<WimImage>
  1594.        Images {
  1595.            get {
  1596.                if (null == m_imageList) {
  1597.  
  1598.                    int imageCount = (int)ImageCount;
  1599.                    m_imageList = new List<WimImage>(imageCount);
  1600.                    for (int i = 0; i < imageCount; i++) {
  1601.  
  1602.                        // Load up each image so it's ready for us.
  1603.                        m_imageList.Add(
  1604.                            new WimImage(this, (uint)i + 1));
  1605.                    }
  1606.                }
  1607.  
  1608.                return m_imageList;
  1609.            }
  1610.        }
  1611.  
  1612.        /// <summary>
  1613.        /// Provides a list of names of the images in the specified WIM container file.
  1614.        /// </summary>
  1615.        public List<string>
  1616.        ImageNames {
  1617.            get {
  1618.                List<string> nameList = new List<string>();
  1619.                foreach (WimImage image in Images) {
  1620.                    nameList.Add(image.ImageName);
  1621.                }
  1622.                return nameList;
  1623.            }
  1624.        }
  1625.  
  1626.        /// <summary>
  1627.        /// Indexer for WIM images inside the WIM container, indexed by the image number.
  1628.        /// The list of Images is 0-based, but the WIM container is 1-based, so we automatically compensate for that.
  1629.        /// this[1] returns the 0th image in the WIM container.
  1630.        /// </summary>
  1631.        /// <param name="ImageIndex">The 1-based index of the image to retrieve.</param>
  1632.        /// <returns>WinImage object.</returns>
  1633.        public WimImage
  1634.        this[int ImageIndex] {
  1635.            get { return Images[ImageIndex - 1]; }
  1636.        }
  1637.  
  1638.        /// <summary>
  1639.        /// Indexer for WIM images inside the WIM container, indexed by the image name.
  1640.        /// WIMs created by different processes sometimes contain different information - including the name.
  1641.        /// Some images have their name stored in the Name field, some in the Flags field, and some in the EditionID field.
  1642.        /// We take all of those into account in while searching the WIM.
  1643.        /// </summary>
  1644.        /// <param name="ImageName"></param>
  1645.        /// <returns></returns>
  1646.        public WimImage
  1647.        this[string ImageName] {
  1648.            get {
  1649.                return
  1650.                    Images.Where(i => (
  1651.                        i.ImageName.ToUpper()  == ImageName.ToUpper() ||
  1652.                        i.ImageFlags.ToUpper() == ImageName.ToUpper() ))
  1653.                    .DefaultIfEmpty(null)
  1654.                        .FirstOrDefault<WimImage>();
  1655.            }
  1656.        }
  1657.  
  1658.        /// <summary>
  1659.        /// Returns the number of images in the WIM container.
  1660.        /// </summary>
  1661.        internal uint
  1662.        ImageCount {
  1663.            get { return NativeMethods.WimGetImageCount(Handle); }
  1664.        }
  1665.  
  1666.        /// <summary>
  1667.        /// Returns an XDocument representation of the XML metadata for the WIM container and associated images.
  1668.        /// </summary>
  1669.        internal XDocument
  1670.        XmlInfo {
  1671.            get {
  1672.  
  1673.                if (null == m_xmlInfo) {
  1674.                    StringBuilder builder;
  1675.                    uint bytes;
  1676.                    if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
  1677.                        throw new Win32Exception();
  1678.                    }
  1679.  
  1680.                    // Ensure the length of the returned bytes to avoid garbage characters at the end.
  1681.                    int charCount = (int)bytes / sizeof(char);
  1682.                    if (null != builder) {
  1683.                        // Get rid of the unicode file marker at the beginning of the XML.
  1684.                        builder.Remove(0, 1);
  1685.                        builder.EnsureCapacity(charCount - 1);
  1686.                        builder.Length = charCount - 1;
  1687.  
  1688.                        // This isn't likely to change while we have the image open, so cache it.
  1689.                        m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
  1690.                    } else {
  1691.                        m_xmlInfo = null;
  1692.                    }
  1693.                }
  1694.  
  1695.                return m_xmlInfo;
  1696.            }
  1697.        }
  1698.  
  1699.        public NativeMethods.WimFileHandle Handle {
  1700.            get;
  1701.            private set;
  1702.        }
  1703.    }
  1704.  
  1705.    public class
  1706.    WimImage {
  1707.  
  1708.        internal XDocument m_xmlInfo;
  1709.  
  1710.        public
  1711.        WimImage(
  1712.            WimFile Container,
  1713.            uint ImageIndex) {
  1714.  
  1715.            if (null == Container) {
  1716.                throw new ArgumentNullException("Container");
  1717.            }
  1718.  
  1719.            if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) {
  1720.                throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container");
  1721.            }
  1722.  
  1723.            if (ImageIndex > Container.ImageCount) {
  1724.                throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file.");
  1725.            }
  1726.  
  1727.            Handle = new NativeMethods.WimImageHandle(Container, ImageIndex);            
  1728.        }
  1729.  
  1730.        public enum
  1731.        Architectures : uint {
  1732.            x86   = 0x0,
  1733.            ARM   = 0x5,
  1734.            IA64  = 0x6,
  1735.            AMD64 = 0x9
  1736.        }
  1737.  
  1738.        public void
  1739.        Close() {
  1740.            if ((!Handle.IsClosed) && (!Handle.IsInvalid)) {
  1741.                Handle.Close();
  1742.            }
  1743.        }
  1744.  
  1745.        public void
  1746.        Apply(
  1747.            string ApplyToPath) {
  1748.  
  1749.            if (string.IsNullOrEmpty(ApplyToPath)) {
  1750.                throw new ArgumentNullException("ApplyToPath");
  1751.            }
  1752.  
  1753.            ApplyToPath = Path.GetFullPath(ApplyToPath);
  1754.  
  1755.            if (!Directory.Exists(ApplyToPath)) {
  1756.                throw new DirectoryNotFoundException("The WIM cannot be applied because the specified directory was not found.");
  1757.            }
  1758.  
  1759.            if (!NativeMethods.WimApplyImage(
  1760.                this.Handle,
  1761.                ApplyToPath,
  1762.                NativeMethods.WimApplyFlags.WimApplyFlagsNone
  1763.            )) {
  1764.                throw new Win32Exception();
  1765.            }
  1766.        }
  1767.  
  1768.        public NativeMethods.WimImageHandle
  1769.        Handle {
  1770.            get;
  1771.            private set;
  1772.        }
  1773.  
  1774.        internal XDocument
  1775.        XmlInfo {
  1776.            get {
  1777.  
  1778.                if (null == m_xmlInfo) {
  1779.                    StringBuilder builder;
  1780.                    uint bytes;
  1781.                    if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) {
  1782.                        throw new Win32Exception();
  1783.                    }
  1784.  
  1785.                    // Ensure the length of the returned bytes to avoid garbage characters at the end.
  1786.                    int charCount = (int)bytes / sizeof(char);
  1787.                    if (null != builder) {
  1788.                        // Get rid of the unicode file marker at the beginning of the XML.
  1789.                        builder.Remove(0, 1);
  1790.                        builder.EnsureCapacity(charCount - 1);
  1791.                        builder.Length = charCount - 1;
  1792.  
  1793.                        // This isn't likely to change while we have the image open, so cache it.
  1794.                        m_xmlInfo = XDocument.Parse(builder.ToString().Trim());
  1795.                    } else {
  1796.                        m_xmlInfo = null;
  1797.                    }
  1798.                }
  1799.  
  1800.                return m_xmlInfo;
  1801.            }
  1802.        }
  1803.  
  1804.        public string
  1805.        ImageIndex {
  1806.            get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; }
  1807.        }
  1808.  
  1809.        public string
  1810.        ImageName {
  1811.            get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; }
  1812.        }
  1813.  
  1814.        public string
  1815.        ImageEditionId {
  1816.            get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; }
  1817.        }
  1818.  
  1819.        public string
  1820.        ImageFlags {
  1821.            get { return XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value; }
  1822.        }
  1823.  
  1824.        public string
  1825.        ImageProductType {
  1826.            get {
  1827.                return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value;
  1828.            }
  1829.        }
  1830.  
  1831.        public string
  1832.        ImageInstallationType {
  1833.            get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; }
  1834.        }
  1835.  
  1836.        public string
  1837.        ImageDescription {
  1838.            get { return XmlInfo.XPathSelectElement("/IMAGE/DESCRIPTION").Value; }
  1839.        }
  1840.  
  1841.        public ulong
  1842.        ImageSize {
  1843.            get { return ulong.Parse(XmlInfo.XPathSelectElement("/IMAGE/TOTALBYTES").Value); }
  1844.        }
  1845.  
  1846.        public Architectures
  1847.        ImageArchitecture {
  1848.            get {
  1849.                int arch = -1;
  1850.                try {
  1851.                    arch = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/ARCH").Value);
  1852.                } catch { }
  1853.  
  1854.                return (Architectures)arch;
  1855.            }
  1856.        }
  1857.  
  1858.        public string
  1859.        ImageDefaultLanguage {
  1860.            get {
  1861.                string lang = null;
  1862.                try {
  1863.                    lang = XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/LANGUAGES/DEFAULT").Value;
  1864.                } catch { }
  1865.  
  1866.                return lang;
  1867.            }
  1868.        }
  1869.  
  1870.        public Version
  1871.        ImageVersion {
  1872.            get {
  1873.                int major = 0;
  1874.                int minor = 0;
  1875.                int build = 0;
  1876.                int revision = 0;
  1877.  
  1878.                try {
  1879.                    major = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MAJOR").Value);
  1880.                    minor = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MINOR").Value);
  1881.                    build = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/BUILD").Value);
  1882.                    revision = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/SPBUILD").Value);
  1883.                } catch { }
  1884.  
  1885.                return (new Version(major, minor, build, revision));
  1886.            }
  1887.        }
  1888.  
  1889.        public string
  1890.        ImageDisplayName {
  1891.            get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYNAME").Value; }
  1892.        }
  1893.  
  1894.        public string
  1895.        ImageDisplayDescription {
  1896.            get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYDESCRIPTION").Value; }
  1897.        }
  1898.    }
  1899.  
  1900.    ///<summary>
  1901.    ///Describes the file that is being processed for the ProcessFileEvent.
  1902.    ///</summary>
  1903.    public class
  1904.    DefaultImageEventArgs : EventArgs {
  1905.        ///<summary>
  1906.        ///Default constructor.
  1907.        ///</summary>
  1908.        public
  1909.        DefaultImageEventArgs(
  1910.            IntPtr wideParameter,
  1911.            IntPtr leftParameter,
  1912.            IntPtr userData) {
  1913.            
  1914.            WideParameter = wideParameter;
  1915.            LeftParameter = leftParameter;
  1916.            UserData      = userData;
  1917.        }
  1918.  
  1919.        ///<summary>
  1920.        ///wParam
  1921.        ///</summary>
  1922.        public IntPtr WideParameter {
  1923.            get;
  1924.            private set;
  1925.        }
  1926.  
  1927.        ///<summary>
  1928.        ///lParam
  1929.        ///</summary>
  1930.        public IntPtr LeftParameter {
  1931.            get;
  1932.            private set;
  1933.        }
  1934.  
  1935.        ///<summary>
  1936.        ///UserData
  1937.        ///</summary>
  1938.        public IntPtr UserData {
  1939.            get;
  1940.            private set;
  1941.        }
  1942.    }
  1943.  
  1944.    ///<summary>
  1945.    ///Describes the file that is being processed for the ProcessFileEvent.
  1946.    ///</summary>
  1947.    public class
  1948.    ProcessFileEventArgs : EventArgs {
  1949.        ///<summary>
  1950.        ///Default constructor.
  1951.        ///</summary>
  1952.        ///<param name="file">Fully qualified path and file name. For example: c:\file.sys.</param>
  1953.        ///<param name="skipFileFlag">Default is false - skip file and continue.
  1954.        ///Set to true to abort the entire image capture.</param>
  1955.        public
  1956.        ProcessFileEventArgs(
  1957.            string file,
  1958.            IntPtr skipFileFlag) {
  1959.  
  1960.            m_FilePath = file;
  1961.            m_SkipFileFlag = skipFileFlag;
  1962.        }
  1963.  
  1964.        ///<summary>
  1965.        ///Skip file from being imaged.
  1966.        ///</summary>
  1967.        public void
  1968.        SkipFile() {
  1969.            byte[] byteBuffer = {
  1970.                    0
  1971.            };
  1972.            int byteBufferSize = byteBuffer.Length;
  1973.            Marshal.Copy(byteBuffer, 0, m_SkipFileFlag, byteBufferSize);
  1974.        }
  1975.  
  1976.        ///<summary>
  1977.        ///Fully qualified path and file name.
  1978.        ///</summary>
  1979.        public string
  1980.        FilePath {
  1981.            get {
  1982.                string stringToReturn = "";
  1983.                if (m_FilePath != null) {
  1984.                    stringToReturn = m_FilePath;
  1985.                }
  1986.                return stringToReturn;
  1987.            }
  1988.        }
  1989.  
  1990.        ///<summary>
  1991.        ///Flag to indicate if the entire image capture should be aborted.
  1992.        ///Default is false - skip file and continue. Setting to true will
  1993.        ///abort the entire image capture.
  1994.        ///</summary>
  1995.        public bool Abort {
  1996.            set { m_Abort = value; }
  1997.            get { return m_Abort;  }
  1998.        }
  1999.  
  2000.        private string m_FilePath;
  2001.        private bool m_Abort;
  2002.        private IntPtr m_SkipFileFlag;
  2003.  
  2004.    }
  2005.  
  2006.    #endregion WIM Interop
  2007.  
  2008.    #region VHD Interop
  2009.    // Based on code written by the Hyper-V Test team.
  2010.    /// <summary>
  2011.    /// The Virtual Hard Disk class provides methods for creating and manipulating Virtual Hard Disk files.
  2012.    /// </summary>
  2013.    public class
  2014.    VirtualHardDisk : IDisposable {
  2015.  
  2016.        #region Member Variables
  2017.  
  2018.        private SafeFileHandle m_virtualHardDiskHandle = null;
  2019.        private string m_filePath = null;
  2020.        private bool m_isDisposed;
  2021.        private NativeMethods.VirtualStorageDeviceType m_deviceType = NativeMethods.VirtualStorageDeviceType.Unknown;
  2022.  
  2023.        #endregion Member Variables
  2024.  
  2025.        #region IDisposable Members
  2026.  
  2027.        /// <summary>
  2028.        /// Disposal method for Virtual Hard Disk objects.
  2029.        /// </summary>
  2030.        public void
  2031.        Dispose() {
  2032.            this.Dispose(true);
  2033.            GC.SuppressFinalize(this);
  2034.        }
  2035.  
  2036.        /// <summary>
  2037.        /// Disposal method for Virtual Hard Disk objects.
  2038.        /// </summary>
  2039.        /// <param name="disposing"></param>
  2040.        public void
  2041.        Dispose(
  2042.            bool disposing) {
  2043.            // Check to see if Dispose has already been called.
  2044.            if (!this.m_isDisposed) {
  2045.                // If disposing equals true, dispose all managed
  2046.                // and unmanaged resources.
  2047.                if (disposing) {
  2048.                    // Dispose managed resources.
  2049.                    if (this.DiskIndex != 0) {
  2050.                        this.Close();
  2051.                    }
  2052.                }
  2053.  
  2054.                // Call the appropriate methods to clean up
  2055.                // unmanaged resources here.
  2056.                // If disposing is false,
  2057.                // only the following code is executed.
  2058.  
  2059.                // Note disposing has been done.
  2060.                m_isDisposed = true;
  2061.            }
  2062.        }
  2063.  
  2064.        #endregion IDisposable Members
  2065.  
  2066.        #region Constructor
  2067.  
  2068.        private VirtualHardDisk(
  2069.            SafeFileHandle Handle,
  2070.            string Path,
  2071.            NativeMethods.VirtualStorageDeviceType DeviceType) {
  2072.            if (Handle.IsInvalid || Handle.IsClosed) {
  2073.                throw new InvalidOperationException("The handle to the Virtual Hard Disk is invalid.");
  2074.            }
  2075.  
  2076.            m_virtualHardDiskHandle = Handle;
  2077.            m_filePath = Path;
  2078.            m_deviceType = DeviceType;
  2079.        }
  2080.  
  2081.        #endregion Constructor
  2082.  
  2083.        #region Gozer the Destructor
  2084.        /// <summary>
  2085.        /// Destroys a VHD object.
  2086.        /// </summary>
  2087.        ~VirtualHardDisk() {
  2088.            this.Dispose(false);
  2089.        }
  2090.  
  2091.        #endregion Gozer the Destructor
  2092.  
  2093.        #region Static Methods
  2094.  
  2095.        #region Sparse Disks
  2096.  
  2097.        /// <summary>
  2098.        /// Abbreviated signature of CreateSparseDisk so it's easier to use from WIM2VHD.
  2099.        /// </summary>
  2100.        /// <param name="virtualStorageDeviceType">The type of disk to create, VHD or VHDX.</param>
  2101.        /// <param name="path">The path of the disk to create.</param>
  2102.        /// <param name="size">The maximum size of the disk to create.</param>
  2103.        /// <param name="overwrite">Overwrite the VHD if it already exists.</param>
  2104.        /// <returns>Virtual Hard Disk object</returns>
  2105.        public static VirtualHardDisk
  2106.        CreateSparseDisk(
  2107.            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
  2108.            string path,
  2109.            ulong size,
  2110.            bool overwrite) {
  2111.  
  2112.            return CreateSparseDisk(
  2113.                path,
  2114.                size,
  2115.                overwrite,
  2116.                null,
  2117.                IntPtr.Zero,
  2118.                (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
  2119.                    ? NativeMethods.DEFAULT_BLOCK_SIZE
  2120.                    : 0,
  2121.                virtualStorageDeviceType,
  2122.                NativeMethods.DISK_SECTOR_SIZE);
  2123.        }
  2124.  
  2125.        /// <summary>
  2126.        /// Creates a new sparse (dynamically expanding) virtual hard disk (.vhd). Supports both sync and async modes.
  2127.        /// The VHD image file uses only as much space on the backing store as needed to store the actual data the VHD currently contains.
  2128.        /// </summary>
  2129.        /// <param name="path">The path and name of the VHD to create.</param>
  2130.        /// <param name="size">The size of the VHD to create in bytes.  
  2131.        /// 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,
  2132.        /// therefore it is possible to successfully create a dynamic VHD with a maximum size larger than the available physical disk free space.
  2133.        /// The maximum size of a dynamic VHD is 2,040 GB.  The minimum size is 3 MB.</param>
  2134.        /// <param name="source">Optional path to pre-populate the new virtual disk object with block data from an existing disk
  2135.        /// This path may refer to a VHD or a physical disk.  Use NULL if you don't want a source.</param>
  2136.        /// <param name="overwrite">If the VHD exists, setting this parameter to 'True' will delete it and create a new one.</param>
  2137.        /// <param name="overlapped">If not null, the operation runs in async mode</param>
  2138.        /// <param name="blockSizeInBytes">Block size for the VHD.</param>
  2139.        /// <param name="virtualStorageDeviceType">VHD format version (VHD1 or VHD2)</param>
  2140.        /// <param name="sectorSizeInBytes">Sector size for the VHD.</param>
  2141.        /// <returns>Returns a SafeFileHandle corresponding to the virtual hard disk that was created.</returns>
  2142.        /// <exception cref="ArgumentOutOfRangeException">Thrown when an invalid size is specified</exception>
  2143.        /// <exception cref="FileNotFoundException">Thrown when source VHD is not found.</exception>
  2144.        /// <exception cref="SecurityException">Thrown when there was an error while creating the default security descriptor.</exception>
  2145.        /// <exception cref="Win32Exception">Thrown when an error occurred while creating the VHD.</exception>
  2146.        public static VirtualHardDisk
  2147.        CreateSparseDisk(
  2148.            string path,
  2149.            ulong size,
  2150.            bool overwrite,
  2151.            string source,
  2152.            IntPtr overlapped,
  2153.            uint blockSizeInBytes,
  2154.            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
  2155.            uint sectorSizeInBytes) {
  2156.  
  2157.            // Validate the virtualStorageDeviceType
  2158.            if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX) {
  2159.  
  2160.                throw (
  2161.                    new ArgumentOutOfRangeException(
  2162.                        "virtualStorageDeviceType",
  2163.                        virtualStorageDeviceType,
  2164.                        "VirtualStorageDeviceType must be VHD or VHDX."
  2165.                ));
  2166.            }
  2167.  
  2168.            // Validate size.  It needs to be a multiple of DISK_SECTOR_SIZE (512)...
  2169.            if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0) {
  2170.  
  2171.                throw (
  2172.                    new ArgumentOutOfRangeException(
  2173.                        "size",
  2174.                        size,
  2175.                        "The size of the virtual disk must be a multiple of 512."
  2176.                ));
  2177.            }
  2178.  
  2179.            if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source))) {
  2180.  
  2181.                throw (
  2182.                    new System.IO.FileNotFoundException(
  2183.                        "Unable to find the source file.",
  2184.                        source
  2185.                ));
  2186.            }
  2187.  
  2188.            if ((overwrite) && (System.IO.File.Exists(path))) {
  2189.  
  2190.                System.IO.File.Delete(path);
  2191.            }
  2192.  
  2193.            NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters();
  2194.  
  2195.            // Select the correct version.
  2196.            createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
  2197.                ? NativeMethods.CreateVirtualDiskVersion.Version1
  2198.                : NativeMethods.CreateVirtualDiskVersion.Version2;
  2199.  
  2200.            createParams.UniqueId                 = Guid.NewGuid();
  2201.            createParams.MaximumSize              = size;
  2202.            createParams.BlockSizeInBytes         = blockSizeInBytes;
  2203.            createParams.SectorSizeInBytes        = sectorSizeInBytes;
  2204.            createParams.ParentPath               = null;
  2205.            createParams.SourcePath               = source;
  2206.            createParams.OpenFlags                = NativeMethods.OpenVirtualDiskFlags.None;
  2207.            createParams.GetInfoOnly              = false;
  2208.            createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType();
  2209.            createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType();
  2210.  
  2211.            //
  2212.            // Create and init a security descriptor.
  2213.            // Since we're creating an essentially blank SD to use with CreateVirtualDisk
  2214.            // the VHD will take on the security values from the parent directory.
  2215.            //
  2216.  
  2217.            NativeMethods.SecurityDescriptor securityDescriptor;
  2218.            if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) {
  2219.  
  2220.                throw (
  2221.                    new SecurityException(
  2222.                        "Unable to initialize the security descriptor for the virtual disk."
  2223.                ));
  2224.            }
  2225.  
  2226.            NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
  2227.            virtualStorageType.DeviceId = virtualStorageDeviceType;
  2228.            virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
  2229.  
  2230.            SafeFileHandle vhdHandle;
  2231.  
  2232.            uint returnCode = NativeMethods.CreateVirtualDisk(
  2233.                ref virtualStorageType,
  2234.                    path,
  2235.                    (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
  2236.                        ? NativeMethods.VirtualDiskAccessMask.All
  2237.                        : NativeMethods.VirtualDiskAccessMask.None,
  2238.                ref securityDescriptor,
  2239.                    NativeMethods.CreateVirtualDiskFlags.None,
  2240.                    0,
  2241.                ref createParams,
  2242.                    overlapped,
  2243.                out vhdHandle);
  2244.  
  2245.            if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode) {
  2246.  
  2247.                throw (
  2248.                    new Win32Exception(
  2249.                        (int)returnCode
  2250.                ));
  2251.            }
  2252.  
  2253.            return new VirtualHardDisk(vhdHandle, path, virtualStorageDeviceType);
  2254.        }
  2255.  
  2256.        #endregion Sparse Disks
  2257.  
  2258.        #region Fixed Disks
  2259.  
  2260.        /// <summary>
  2261.        /// Abbreviated signature of CreateFixedDisk so it's easier to use from WIM2VHD.
  2262.        /// </summary>
  2263.        /// <param name="virtualStorageDeviceType">The type of disk to create, VHD or VHDX.</param>
  2264.        /// <param name="path">The path of the disk to create.</param>
  2265.        /// <param name="size">The maximum size of the disk to create.</param>
  2266.        /// <param name="overwrite">Overwrite the VHD if it already exists.</param>
  2267.        /// <returns>Virtual Hard Disk object</returns>
  2268.        public static VirtualHardDisk
  2269.        CreateFixedDisk(
  2270.            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
  2271.            string path,
  2272.            ulong size,
  2273.            bool overwrite) {
  2274.  
  2275.            return CreateFixedDisk(
  2276.                path,
  2277.                size,
  2278.                overwrite,
  2279.                null,
  2280.                IntPtr.Zero,
  2281.                0,
  2282.                virtualStorageDeviceType,
  2283.                NativeMethods.DISK_SECTOR_SIZE);
  2284.        }
  2285.  
  2286.        /// <summary>
  2287.        /// Creates a fixed-size Virtual Hard Disk. Supports both sync and async modes. This methods always calls the V2 version of the
  2288.        /// CreateVirtualDisk API, and creates VHD2.
  2289.        /// </summary>
  2290.        /// <param name="path">The path and name of the VHD to create.</param>
  2291.        /// <param name="size">The size of the VHD to create in bytes.  
  2292.        /// The VHD image file is pre-allocated on the backing store for the maximum size requested.
  2293.        /// The maximum size of a dynamic VHD is 2,040 GB.  The minimum size is 3 MB.</param>
  2294.        /// <param name="source">Optional path to pre-populate the new virtual disk object with block data from an existing disk
  2295.        /// This path may refer to a VHD or a physical disk.  Use NULL if you don't want a source.</param>
  2296.        /// <param name="overwrite">If the VHD exists, setting this parameter to 'True' will delete it and create a new one.</param>
  2297.        /// <param name="overlapped">If not null, the operation runs in async mode</param>
  2298.        /// <param name="blockSizeInBytes">Block size for the VHD.</param>
  2299.        /// <param name="virtualStorageDeviceType">Virtual storage device type: VHD1 or VHD2.</param>
  2300.        /// <param name="sectorSizeInBytes">Sector size for the VHD.</param>
  2301.        /// <returns>Returns a SafeFileHandle corresponding to the virtual hard disk that was created.</returns>
  2302.        /// <remarks>Creating a fixed disk can be a time consuming process!</remarks>  
  2303.        /// <exception cref="ArgumentOutOfRangeException">Thrown when an invalid size or wrong virtual storage device type is specified.</exception>
  2304.        /// <exception cref="FileNotFoundException">Thrown when source VHD is not found.</exception>
  2305.        /// <exception cref="SecurityException">Thrown when there was an error while creating the default security descriptor.</exception>
  2306.        /// <exception cref="Win32Exception">Thrown when an error occurred while creating the VHD.</exception>
  2307.        public static VirtualHardDisk
  2308.        CreateFixedDisk(
  2309.            string path,
  2310.            ulong size,
  2311.            bool overwrite,
  2312.            string source,
  2313.            IntPtr overlapped,
  2314.            uint blockSizeInBytes,
  2315.            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType,
  2316.            uint sectorSizeInBytes) {
  2317.  
  2318.            // Validate the virtualStorageDeviceType
  2319.            if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX) {
  2320.  
  2321.                throw (
  2322.                    new ArgumentOutOfRangeException(
  2323.                        "virtualStorageDeviceType",
  2324.                        virtualStorageDeviceType,
  2325.                        "VirtualStorageDeviceType must be VHD or VHDX."
  2326.                ));
  2327.            }
  2328.  
  2329.            // Validate size.  It needs to be a multiple of DISK_SECTOR_SIZE (512)...
  2330.            if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0) {
  2331.  
  2332.                throw (
  2333.                    new ArgumentOutOfRangeException(
  2334.                        "size",
  2335.                        size,
  2336.                        "The size of the virtual disk must be a multiple of 512."
  2337.                ));
  2338.            }
  2339.  
  2340.            if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source))) {
  2341.  
  2342.                throw (
  2343.                    new System.IO.FileNotFoundException(
  2344.                        "Unable to find the source file.",
  2345.                        source
  2346.                ));
  2347.            }
  2348.  
  2349.            if ((overwrite) && (System.IO.File.Exists(path))) {
  2350.  
  2351.                System.IO.File.Delete(path);
  2352.            }
  2353.  
  2354.            NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters();
  2355.  
  2356.            // Select the correct version.
  2357.            createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
  2358.                ? NativeMethods.CreateVirtualDiskVersion.Version1
  2359.                : NativeMethods.CreateVirtualDiskVersion.Version2;
  2360.  
  2361.            createParams.UniqueId                 = Guid.NewGuid();
  2362.            createParams.MaximumSize              = size;
  2363.            createParams.BlockSizeInBytes         = blockSizeInBytes;
  2364.            createParams.SectorSizeInBytes        = sectorSizeInBytes;
  2365.            createParams.ParentPath               = null;
  2366.            createParams.SourcePath               = source;
  2367.            createParams.OpenFlags                = NativeMethods.OpenVirtualDiskFlags.None;
  2368.            createParams.GetInfoOnly              = false;
  2369.            createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType();
  2370.            createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType();
  2371.  
  2372.            //
  2373.            // Create and init a security descriptor.
  2374.            // Since we're creating an essentially blank SD to use with CreateVirtualDisk
  2375.            // the VHD will take on the security values from the parent directory.
  2376.            //
  2377.  
  2378.            NativeMethods.SecurityDescriptor securityDescriptor;
  2379.            if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) {
  2380.                throw (
  2381.                    new SecurityException(
  2382.                        "Unable to initialize the security descriptor for the virtual disk."
  2383.                ));
  2384.            }
  2385.  
  2386.            NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
  2387.            virtualStorageType.DeviceId = virtualStorageDeviceType;
  2388.            virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
  2389.  
  2390.            SafeFileHandle vhdHandle;
  2391.  
  2392.            uint returnCode = NativeMethods.CreateVirtualDisk(
  2393.                ref virtualStorageType,
  2394.                    path,
  2395.                    (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
  2396.                        ? NativeMethods.VirtualDiskAccessMask.All
  2397.                        : NativeMethods.VirtualDiskAccessMask.None,
  2398.                ref securityDescriptor,
  2399.                    NativeMethods.CreateVirtualDiskFlags.FullPhysicalAllocation,
  2400.                    0,
  2401.                ref createParams,
  2402.                    overlapped,
  2403.                out vhdHandle);
  2404.  
  2405.            if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode) {
  2406.  
  2407.                throw (
  2408.                    new Win32Exception(
  2409.                        (int)returnCode
  2410.                ));
  2411.            }
  2412.  
  2413.            return new VirtualHardDisk(vhdHandle, path, virtualStorageDeviceType);
  2414.        }
  2415.  
  2416.        #endregion Fixed Disks
  2417.  
  2418.        #region Open
  2419.  
  2420.        /// <summary>
  2421.        /// Opens a virtual hard disk (VHD) using the V2 of OpenVirtualDisk Win32 API for use, allowing you to explicitly specify OpenVirtualDiskFlags,
  2422.        /// Read/Write depth, and Access Mask information.
  2423.        /// </summary>
  2424.        /// <param name="path">The path and name of the Virtual Hard Disk file to open.</param>
  2425.        /// <param name="accessMask">Contains the bit mask for specifying access rights to a virtual hard disk (VHD).  Default is All.</param>
  2426.        /// <param name="readWriteDepth">Indicates the number of stores, beginning with the child, of the backing store chain to open as read/write.
  2427.        /// The remaining stores in the differencing chain will be opened read-only. This is necessary for merge operations to succeed.  Default is 0x1.</param>
  2428.        /// <param name="flags">An OpenVirtualDiskFlags object to modify the way the Virtual Hard Disk is opened.  Default is Unknown.</param>
  2429.        /// <param name="virtualStorageDeviceType">VHD Format Version (VHD1 or VHD2)</param>
  2430.        /// <returns>VirtualHardDisk object</returns>
  2431.        /// <exception cref="FileNotFoundException">Thrown if the VHD at path is not found.</exception>
  2432.        /// <exception cref="Win32Exception">Thrown if an error occurred while opening the VHD.</exception>
  2433.        public static VirtualHardDisk
  2434.        Open(
  2435.            string path,
  2436.            NativeMethods.VirtualDiskAccessMask accessMask,
  2437.            uint readWriteDepth,
  2438.            NativeMethods.OpenVirtualDiskFlags flags,
  2439.            NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType) {
  2440.  
  2441.            if (!File.Exists(path)) {
  2442.                throw new FileNotFoundException("The specified VHD was not found.  Please check your path and try again.", path);
  2443.            }
  2444.  
  2445.            NativeMethods.OpenVirtualDiskParameters openParams = new NativeMethods.OpenVirtualDiskParameters();
  2446.  
  2447.            // Select the correct version.
  2448.            openParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD)
  2449.                ? NativeMethods.OpenVirtualDiskVersion.Version1
  2450.                : NativeMethods.OpenVirtualDiskVersion.Version2;
  2451.  
  2452.            openParams.GetInfoOnly = false;
  2453.  
  2454.            NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType();
  2455.            virtualStorageType.DeviceId = virtualStorageDeviceType;
  2456.  
  2457.            virtualStorageType.VendorId = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.Unknown)
  2458.                ? virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorUnknown
  2459.                : virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft;
  2460.  
  2461.            SafeFileHandle vhdHandle;
  2462.  
  2463.            uint returnCode = NativeMethods.OpenVirtualDisk(
  2464.                ref virtualStorageType,
  2465.                    path,
  2466.                    accessMask,
  2467.                    flags,
  2468.                ref openParams,
  2469.                out vhdHandle);
  2470.  
  2471.            if (NativeMethods.ERROR_SUCCESS != returnCode) {
  2472.                throw new Win32Exception((int)returnCode);
  2473.            }
  2474.  
  2475.            return new VirtualHardDisk(vhdHandle, path, virtualStorageDeviceType);
  2476.        }
  2477.  
  2478.        #endregion Open
  2479.  
  2480.        #region Other
  2481.  
  2482.        /// <summary>
  2483.        /// Retrieves a collection of drive letters that are currently available on the system.
  2484.        /// </summary>
  2485.        /// <remarks>Drives A and B are not included in the collection, even if they are available.</remarks>
  2486.        /// <returns>A collection of drive letters that are currently available on the system.</returns>
  2487.        public static ReadOnlyCollection<Char>
  2488.        GetAvailableDriveLetters() {
  2489.  
  2490.            List<Char> availableDrives = new List<Char>();
  2491.            for (int i = (byte)'C'; i <= (byte)'Z'; i++) {
  2492.                availableDrives.Add((char)i);
  2493.            }
  2494.  
  2495.            foreach (string drive in System.Environment.GetLogicalDrives()) {
  2496.                availableDrives.Remove(drive.ToUpper(CultureInfo.InvariantCulture)[0]);
  2497.            }
  2498.  
  2499.            return new ReadOnlyCollection<char>(availableDrives);
  2500.        }
  2501.  
  2502.        /// <summary>
  2503.        /// Gets the first available drive letter on the current system.
  2504.        /// </summary>
  2505.        /// <remarks>Drives A and B will not be returned, even if they are available.</remarks>
  2506.        /// <returns>Char representing the first available drive letter.</returns>
  2507.        public static char
  2508.        GetFirstAvailableDriveLetter() {
  2509.            return GetAvailableDriveLetters()[0];
  2510.        }
  2511.  
  2512.        #endregion Other
  2513.  
  2514.        #endregion Static Methods
  2515.  
  2516.        #region AsyncHelpers
  2517.  
  2518.        /// <summary>
  2519.        /// Creates a NativeOverlapped object, initializes its EventHandle property, and pins the object to the memory.
  2520.        /// This overlapped objects are useful when executing VHD meta-ops in async mode.
  2521.        /// </summary>
  2522.        /// <returns>Returns the GCHandle for the pinned overlapped structure</returns>
  2523.        public static GCHandle
  2524.        CreatePinnedOverlappedObject() {
  2525.            NativeOverlapped overlapped = new NativeOverlapped();
  2526.            overlapped.EventHandle = NativeMethods.CreateEvent(IntPtr.Zero, true, false, null);
  2527.  
  2528.            GCHandle handleForOverllapped = GCHandle.Alloc(overlapped, GCHandleType.Pinned);
  2529.  
  2530.            return handleForOverllapped;
  2531.        }
  2532.  
  2533.        /// <summary>
  2534.        /// GetVirtualDiskOperationProgress API allows getting progress info for the async virtual disk operations (ie. Online Mirror)
  2535.        /// </summary>
  2536.        /// <param name="progress"></param>
  2537.        /// <param name="overlapped"></param>
  2538.        /// <returns></returns>
  2539.        /// <exception cref="Win32Exception">Thrown when an error occurred while mirroring the VHD.</exception>
  2540.        public uint
  2541.        GetVirtualDiskOperationProgress(
  2542.            ref NativeMethods.VirtualDiskProgress progress,
  2543.                IntPtr overlapped) {
  2544.            uint returnCode = NativeMethods.GetVirtualDiskOperationProgress(
  2545.                    this.m_virtualHardDiskHandle,
  2546.                    overlapped,
  2547.                ref progress);
  2548.  
  2549.            return returnCode;
  2550.        }
  2551.  
  2552.        #endregion AsyncHelpers
  2553.  
  2554.        #region Public Methods
  2555.  
  2556.        /// <summary>
  2557.        /// Closes all open handles to the Virtual Hard Disk object.
  2558.        /// If the VHD is currently attached, and the PermanentLifetime was not specified, this operation will detach it.
  2559.        /// </summary>
  2560.        public void
  2561.        Close() {
  2562.            m_virtualHardDiskHandle.Close();
  2563.        }
  2564.  
  2565.        /// <summary>
  2566.        /// Attaches a virtual hard disk (VHD) by locating an appropriate VHD provider to accomplish the attachment.
  2567.        /// </summary>
  2568.        /// <param name="attachVirtualDiskFlags">
  2569.        /// A combination of values from the attachVirtualDiskFlags enumeration which will dictate how the behavior of the VHD once mounted.
  2570.        /// </param>
  2571.        /// <exception cref="Win32Exception">Thrown when an error occurred while attaching the VHD.</exception>
  2572.        /// <exception cref="SecurityException">Thrown when an error occurred while creating the default security descriptor.</exception>
  2573.        public void
  2574.        Attach(
  2575.            NativeMethods.AttachVirtualDiskFlags attachVirtualDiskFlags) {
  2576.  
  2577.            if (!this.IsAttached) {
  2578.  
  2579.                // Get the current disk index.  We need it later.
  2580.                int diskIndex = this.DiskIndex;
  2581.  
  2582.                NativeMethods.AttachVirtualDiskParameters attachParameters = new NativeMethods.AttachVirtualDiskParameters();
  2583.  
  2584.                // For attach, the correct version is always Version1 for Win7 and Win8.
  2585.                attachParameters.Version = NativeMethods.AttachVirtualDiskVersion.Version1;
  2586.                attachParameters.Reserved = 0;
  2587.  
  2588.                NativeMethods.SecurityDescriptor securityDescriptor;
  2589.                if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) {
  2590.  
  2591.                    throw (new SecurityException("Unable to initialize the security descriptor for the virtual disk."));
  2592.                }
  2593.  
  2594.                uint returnCode = NativeMethods.AttachVirtualDisk(
  2595.                         m_virtualHardDiskHandle,
  2596.                    ref  securityDescriptor,
  2597.                         attachVirtualDiskFlags,
  2598.                         0,
  2599.                    ref  attachParameters,
  2600.                         IntPtr.Zero);
  2601.  
  2602.                switch (returnCode) {
  2603.  
  2604.                    case NativeMethods.ERROR_SUCCESS:
  2605.                        break;
  2606.  
  2607.                    default:
  2608.                        throw new Win32Exception((int)returnCode);
  2609.                }
  2610.  
  2611.                // There's apparently a bit of a timing issue here on some systems.
  2612.                // If the disk index isn't updated, keep checking once per second for five seconds.
  2613.                // If it's not updated after that, it's probably not our fault.
  2614.                short attempts = 5;
  2615.                while ((attempts-- >= 0) && (diskIndex == this.DiskIndex)) {
  2616.                    System.Threading.Thread.Sleep(1000);
  2617.                }
  2618.            }
  2619.        }
  2620.  
  2621.        /// <summary>
  2622.        /// Attaches a virtual hard disk (VHD) by locating an appropriate VHD provider to accomplish the attachment.
  2623.        /// </summary>
  2624.        /// <remarks>
  2625.        /// This method attaches the VHD with no flags.
  2626.        /// </remarks>
  2627.        /// <exception cref="Win32Exception">Thrown when an error occurred while attaching the VHD.</exception>
  2628.        /// <exception cref="SecurityException">Thrown when an error occurred while creating the default security descriptor.</exception>
  2629.        public void
  2630.        Attach() {
  2631.  
  2632.            this.Attach(NativeMethods.AttachVirtualDiskFlags.None);
  2633.        }
  2634.  
  2635.        /// <summary>
  2636.        /// Unsurfaces (detaches) a virtual hard disk (VHD) by locating an appropriate VHD provider to accomplish the operation.
  2637.        /// </summary>
  2638.        public void
  2639.        Detach() {
  2640.  
  2641.            if (this.IsAttached) {
  2642.                uint returnCode = NativeMethods.DetachVirtualDisk(
  2643.                    m_virtualHardDiskHandle,
  2644.                    NativeMethods.DetachVirtualDiskFlag.None,
  2645.                    0);
  2646.  
  2647.                switch (returnCode) {
  2648.  
  2649.                    case NativeMethods.ERROR_NOT_FOUND:
  2650.                    // There's nothing to do here.  The device wasn't found, which means there's a
  2651.                    // really good chance that it wasn't attached to begin with.
  2652.                    // And, since we were asked to detach it anyway, we can assume that the system
  2653.                    // is already in the desired state.
  2654.                    case NativeMethods.ERROR_SUCCESS:
  2655.                        break;
  2656.  
  2657.                    default:
  2658.                        throw new Win32Exception((int)returnCode);
  2659.                }
  2660.            }
  2661.        }
  2662.  
  2663.        /// <summary>
  2664.        /// Reduces the size of the virtual hard disk (VHD) backing store file. Supports both sync and async modes.
  2665.        /// </summary>
  2666.        /// <param name="overlapped">If not null, the operation runs in async mode</param>
  2667.        public uint
  2668.        Compact(IntPtr overlapped) {
  2669.            return this.Compact(
  2670.                overlapped,
  2671.                NativeMethods.CompactVirtualDiskFlags.None);
  2672.        }
  2673.  
  2674.        /// <summary>
  2675.        /// Reduces the size of the virtual hard disk (VHD) backing store file. Supports both sync and async modes.
  2676.        /// </summary>
  2677.        /// <param name="overlapped">If not null, the operation runs in async mode</param>
  2678.        /// <param name="flags">Flags for Compact operation</param>
  2679.        public uint
  2680.        Compact(
  2681.            IntPtr overlapped,
  2682.            NativeMethods.CompactVirtualDiskFlags flags) {
  2683.  
  2684.            NativeMethods.CompactVirtualDiskParameters compactParams = new NativeMethods.CompactVirtualDiskParameters();
  2685.            compactParams.Version = NativeMethods.CompactVirtualDiskVersion.Version1;
  2686.  
  2687.            uint returnCode = NativeMethods.CompactVirtualDisk(
  2688.                m_virtualHardDiskHandle,
  2689.                flags,
  2690.            ref compactParams,
  2691.                overlapped);
  2692.  
  2693.            if ((overlapped == IntPtr.Zero && NativeMethods.ERROR_SUCCESS != returnCode) ||
  2694.                (overlapped != IntPtr.Zero && NativeMethods.ERROR_IO_PENDING != returnCode)) {
  2695.                throw new Win32Exception((int)returnCode);
  2696.            }
  2697.  
  2698.            return returnCode;
  2699.        }
  2700.  
  2701.  
  2702.        #endregion Public Methods
  2703.  
  2704.        #region Public Properties
  2705.  
  2706.        /// <summary>
  2707.        /// The SafeFileHandle object for the opened VHD.
  2708.        /// </summary>
  2709.        public SafeFileHandle
  2710.        VirtualHardDiskHandle {
  2711.            get {
  2712.                return m_virtualHardDiskHandle;
  2713.            }
  2714.        }
  2715.  
  2716.        /// <summary>
  2717.        /// Indicates the index of the disk when attached.
  2718.        /// If the virtual hard disk is not currently attached, -1 will be returned.
  2719.        /// </summary>
  2720.        public int
  2721.        DiskIndex {
  2722.            get {
  2723.                string path = PhysicalPath;
  2724.  
  2725.                if (null != path) {
  2726.  
  2727.                    Match match = Regex.Match(path, @"\d+$"); // look for the last digits in the path
  2728.                    return System.Convert.ToInt32(match.Value, CultureInfo.InvariantCulture);
  2729.                } else {
  2730.  
  2731.                    return -1;
  2732.                }
  2733.            }
  2734.        }
  2735.  
  2736.        /// <summary>
  2737.        /// Indicates whether the current Virtual Hard Disk is attached to the system.
  2738.        /// </summary>
  2739.        public bool
  2740.        IsAttached {
  2741.            get {
  2742.                return (this.DiskIndex != -1);
  2743.            }
  2744.        }
  2745.  
  2746.        /// <summary>
  2747.        /// Retrieves the path to the physical device object that contains a virtual hard disk (VHD), if the VHD is attached.
  2748.        /// If it is not attached, NULL will be returned.
  2749.        /// </summary>
  2750.        public string
  2751.        PhysicalPath {
  2752.            get {
  2753.                uint pathSize = 1024;  // Isn't MAX_PATH 255?
  2754.                StringBuilder path = new StringBuilder((int)pathSize);
  2755.                uint returnCode = 0;
  2756.  
  2757.                returnCode = NativeMethods.GetVirtualDiskPhysicalPath(
  2758.                        m_virtualHardDiskHandle,
  2759.                    ref pathSize,
  2760.                        path);
  2761.  
  2762.                if (NativeMethods.ERROR_ERROR_DEV_NOT_EXIST == returnCode) {
  2763.  
  2764.                    return null;
  2765.                } else if (NativeMethods.ERROR_SUCCESS == returnCode) {
  2766.  
  2767.                    return path.ToString();
  2768.                } else {
  2769.  
  2770.                    throw new Win32Exception((int)returnCode);
  2771.                }
  2772.            }
  2773.        }
  2774.  
  2775.        #endregion Public Properties
  2776.    }
  2777.  
  2778.    #endregion VHD Interop
  2779. }
  2780. "@
  2781.  
  2782.     #region Helper Functions
  2783.  
  2784.     ##########################################################################################
  2785.     #                                   Helper Functions
  2786.     ##########################################################################################
  2787.  
  2788.     <#
  2789.         Functions to mount and dismount registry hives.
  2790.         These hives will automatically be accessible via the HKLM:\ registry PSDrive.
  2791.  
  2792.         It should be noted that I have more confidence in using the RegLoadKey and
  2793.         RegUnloadKey Win32 APIs than I do using REG.EXE - it just seems like we should
  2794.         do things ourselves if we can, instead of using yet another binary.
  2795.  
  2796.         Consider this a TODO for future versions.
  2797.     #>
  2798.     Function Mount-RegistryHive {
  2799.         [CmdletBinding()]
  2800.         param(
  2801.             [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
  2802.             [System.IO.FileInfo]
  2803.             [ValidateNotNullOrEmpty()]
  2804.             [ValidateScript({ $_.Exists })]
  2805.             $Hive
  2806.         )
  2807.  
  2808.         $mountKey = [System.Guid]::NewGuid().ToString()
  2809.         $regPath  = "REG.EXE"
  2810.  
  2811.         if (Test-Path HKLM:\$mountKey) {
  2812.             throw "The registry path already exists.  I should just regenerate it, but I'm lazy."
  2813.         }
  2814.  
  2815.         $regArgs = (
  2816.             "LOAD",
  2817.             "HKLM\$mountKey",
  2818.             $Hive.Fullname
  2819.         )
  2820.         try {
  2821.  
  2822.             Run-Executable -Executable $regPath -Arguments $regArgs
  2823.  
  2824.         } catch {
  2825.             throw
  2826.         }
  2827.  
  2828.         # Set a global variable containing the name of the mounted registry key
  2829.         # so we can unmount it if there's an error.
  2830.         $global:mountedHive = $mountKey
  2831.  
  2832.         return $mountKey
  2833.     }
  2834.  
  2835.     ##########################################################################################
  2836.  
  2837.     Function Dismount-RegistryHive {
  2838.         [CmdletBinding()]
  2839.         param(
  2840.             [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
  2841.             [string]
  2842.             [ValidateNotNullOrEmpty()]
  2843.             $HiveMountPoint
  2844.         )
  2845.  
  2846.         $regPath = "REG.EXE"
  2847.  
  2848.         $regArgs = (
  2849.             "UNLOAD",
  2850.             "HKLM\$($HiveMountPoint)"
  2851.         )
  2852.  
  2853.         Run-Executable -Executable $regPath -Arguments $regArgs
  2854.  
  2855.         $global:mountedHive = $null
  2856.     }
  2857.  
  2858.     ##########################################################################################
  2859.  
  2860.     Function
  2861.     Apply-BCDStoreChanges {
  2862.         [CmdletBinding()]
  2863.         param(
  2864.             [Parameter(Mandatory = $true)]
  2865.             [string]
  2866.             [ValidateNotNullOrEmpty()]
  2867.             $BcdStoreFile,
  2868.  
  2869.             [Parameter()]
  2870.             [string]
  2871.             [ValidateNotNullOrEmpty()]
  2872.             [ValidateScript({ ($_ -eq $PARTITION_STYLE_MBR) -or ($_ -eq $PARTITON_STYLE_GPT) })]
  2873.             $PartitionStyle = $PARTITION_STYLE_MBR,
  2874.  
  2875.             [Parameter()]
  2876.             [UInt64]
  2877.             [ValidateScript({ $_ -ge 0 })]
  2878.             $DiskSignature,
  2879.  
  2880.             [Parameter()]
  2881.             [UInt64]
  2882.             [ValidateScript({ $_ -ge 0 })]
  2883.             $PartitionOffset
  2884.         )
  2885.  
  2886.         #########  Set Constants #########
  2887.         $BOOTMGR_ID              = "{9DEA862C-5CDD-4E70-ACC1-F32B344D4795}"
  2888.         $DEFAULT_TYPE            = 0x23000003
  2889.         $APPLICATION_DEVICE_TYPE = 0x11000001
  2890.         $OS_DEVICE_TYPE          = 0x21000001
  2891.         ##################################
  2892.  
  2893.         Write-W2VInfo "Opening $($BcdStoreFile) for configuration..."
  2894.         Write-W2VTrace "Partition Style : $PartitionStyle"
  2895.         Write-W2VTrace "Disk Signature  : $DiskSignature"
  2896.         Write-W2VTrace "Partition Offset: $PartitionOffset"
  2897.  
  2898.         $conn    = New-Object Management.ConnectionOptions
  2899.         $scope   = New-Object Management.ManagementScope -ArgumentList "\\.\ROOT\WMI", $conn
  2900.         $scope.Connect()
  2901.  
  2902.         $path    = New-Object Management.ManagementPath `
  2903.                    -ArgumentList "\\.\ROOT\WMI:BCDObject.Id=`"$($BOOTMGR_ID)`",StoreFilePath=`"$($BcdStoreFile.Replace('\', '\\'))`""
  2904.         $options = New-Object Management.ObjectGetOptions
  2905.         $bootMgr = New-Object Management.ManagementObject -ArgumentList $scope, $path, $options
  2906.  
  2907.         try {
  2908.             $bootMgr.Get()
  2909.         } catch {
  2910.             throw "Could not get the BootMgr object from the Virtual Disks BCDStore."
  2911.         }
  2912.    
  2913.         Write-W2VTrace "Setting Qualified Partition Device Element for Virtual Disk boot..."
  2914.    
  2915.    
  2916.         $ret = $bootMgr.SetQualifiedPartitionDeviceElement($APPLICATION_DEVICE_TYPE, $PartitionStyle, $DiskSignature, $PartitionOffset)
  2917.         if (!$ret.ReturnValue) {
  2918.             throw "Unable to set Qualified Partition Device Element in Virtual Disks BCDStore."
  2919.         }
  2920.  
  2921.         Write-W2VTrace "Getting the default boot entry..."
  2922.         $defaultBootEntryId = ($bootMgr.GetElement($DEFAULT_TYPE)).Element.Id
  2923.  
  2924.         Write-W2VTrace "Getting the OS Loader..."
  2925.  
  2926.         $path    = New-Object Management.ManagementPath `
  2927.                  -ArgumentList "\\.\ROOT\WMI:BCDObject.Id=`"$($defaultBootEntryId)`",StoreFilePath=`"$($BcdStoreFile.Replace('\', '\\'))`""
  2928.  
  2929.         $osLoader= New-Object Management.ManagementObject -ArgumentList $scope, $path, $options
  2930.  
  2931.         try {
  2932.             $osLoader.Get()
  2933.         } catch {
  2934.             throw "Could not get the OS Loader..."
  2935.         }
  2936.  
  2937.         Write-W2VTrace "Setting Qualified Partition Device Element in the OS Loader Application..."
  2938.         $ret = $osLoader.SetQualifiedPartitionDeviceElement($APPLICATION_DEVICE_TYPE, $PartitionStyle, $DiskSignature, $PartitionOffset)
  2939.         if (!$ret.ReturnValue) {
  2940.             throw "Could not set Qualified Partition Device Element in the OS Loader Application."
  2941.         }
  2942.  
  2943.         Write-W2VTrace "Setting Qualified Partition Device Element in the OS Loader Device..."
  2944.         $ret = $osLoader.SetQualifiedPartitionDeviceElement($OS_DEVICE_TYPE, $PartitionStyle, $DiskSignature, $PartitionOffset)
  2945.         if (!$ret.ReturnValue) {
  2946.             throw "Could not set Qualified Partition Device Element in the OS Loader Device."
  2947.         }
  2948.  
  2949.         Write-W2VInfo "BCD configuration complete. Moving on..."
  2950.     }
  2951.  
  2952.     ##########################################################################################
  2953.  
  2954.     function
  2955.     Test-Admin {
  2956.         <#
  2957.             .SYNOPSIS
  2958.                 Short function to determine whether the logged-on user is an administrator.
  2959.  
  2960.             .EXAMPLE
  2961.                 Do you honestly need one?  There are no parameters!
  2962.  
  2963.             .OUTPUTS
  2964.                 $true if user is admin.
  2965.                 $false if user is not an admin.
  2966.         #>
  2967.         [CmdletBinding()]
  2968.         param()
  2969.  
  2970.         $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  2971.         $isAdmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
  2972.         Write-W2VTrace "isUserAdmin? $isAdmin"
  2973.  
  2974.         return $isAdmin
  2975.     }
  2976.  
  2977.     ##########################################################################################
  2978.  
  2979.     function
  2980.     Test-WindowsVersion {
  2981.         $os = Get-WmiObject -Class Win32_OperatingSystem
  2982.         $isWin8 = (($os.Version -ge 6.2) -and ($os.BuildNumber -ge $lowestSupportedBuild))
  2983.  
  2984.         Write-W2VTrace "isWindows8? $isWin8"
  2985.         return $isWin8
  2986.     }
  2987.  
  2988.     ##########################################################################################
  2989.  
  2990.     function
  2991.     Write-W2VInfo {
  2992.     # Function to make the Write-Host output a bit prettier.
  2993.         [CmdletBinding()]
  2994.         param(
  2995.             [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
  2996.             [string]
  2997.             [ValidateNotNullOrEmpty()]
  2998.             $text
  2999.         )
  3000.         Write-Host "INFO   : $($text)" -ForegroundColor White
  3001.     }
  3002.  
  3003.     ##########################################################################################
  3004.  
  3005.     function
  3006.     Write-W2VTrace {
  3007.     # Function to make the Write-Verbose output... well... exactly the same as it was before.
  3008.         [CmdletBinding()]
  3009.         param(
  3010.             [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
  3011.             [string]
  3012.             [ValidateNotNullOrEmpty()]
  3013.             $text
  3014.         )
  3015.         Write-Verbose $text
  3016.     }
  3017.  
  3018.     ##########################################################################################
  3019.  
  3020.     function
  3021.     Write-W2VError {
  3022.     # Function to make the Write-Host (NOT Write-Error) output prettier in the case of an error.
  3023.         [CmdletBinding()]
  3024.         param(
  3025.             [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
  3026.             [string]
  3027.             [ValidateNotNullOrEmpty()]
  3028.             $text
  3029.         )
  3030.         Write-Host "ERROR  : $($text)" -ForegroundColor Red
  3031.     }
  3032.  
  3033.     ##########################################################################################
  3034.  
  3035.     function
  3036.     Write-W2VWarn {
  3037.     # Function to make the Write-Host (NOT Write-Warning) output prettier.
  3038.         [CmdletBinding()]
  3039.         param(
  3040.             [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
  3041.             [string]
  3042.             [ValidateNotNullOrEmpty()]
  3043.             $text
  3044.         )
  3045.         Write-Host "WARN   : $($text)" -ForegroundColor Yellow
  3046.     }
  3047.  
  3048.     ##########################################################################################
  3049.  
  3050.     function
  3051.     Run-Executable {
  3052.         <#
  3053.             .SYNOPSIS
  3054.                 Runs an external executable file, and validates the error level.
  3055.  
  3056.             .PARAMETER Executable
  3057.                 The path to the executable to run and monitor.
  3058.  
  3059.             .PARAMETER Arguments
  3060.                 An array of arguments to pass to the executable when it's executed.
  3061.  
  3062.             .PARAMETER SuccessfulErrorCode
  3063.                 The error code that means the executable ran successfully.
  3064.                 The default value is 0.  
  3065.         #>
  3066.  
  3067.         [CmdletBinding()]
  3068.         param(
  3069.             [Parameter(Mandatory=$true)]
  3070.             [string]
  3071.             [ValidateNotNullOrEmpty()]
  3072.             $Executable,
  3073.  
  3074.             [Parameter(Mandatory=$true)]
  3075.             [string[]]
  3076.             [ValidateNotNullOrEmpty()]
  3077.             $Arguments,
  3078.  
  3079.             [Parameter()]
  3080.             [int]
  3081.             [ValidateNotNullOrEmpty()]
  3082.             $SuccessfulErrorCode = 0
  3083.  
  3084.         )
  3085.  
  3086.         Write-W2VTrace "Running $Executable $Arguments"
  3087.         $ret = Start-Process           `
  3088.             -FilePath $Executable      `
  3089.             -ArgumentList $Arguments   `
  3090.             -NoNewWindow               `
  3091.             -Wait                      `
  3092.             -RedirectStandardOutput "$($env:temp)\$($scriptName)\$($sessionKey)\$($Executable)-StandardOutput.txt" `
  3093.             -RedirectStandardError  "$($env:temp)\$($scriptName)\$($sessionKey)\$($Executable)-StandardError.txt"  `
  3094.             -Passthru
  3095.  
  3096.         Write-W2VTrace "Return code was $($ret.ExitCode)."
  3097.  
  3098.         if ($ret.ExitCode -ne $SuccessfulErrorCode) {
  3099.             throw "$Executable failed with code $($ret.ExitCode)!"
  3100.         }
  3101.     }
  3102.  
  3103.     ##########################################################################################
  3104.     Function Test-IsNetworkLocation {
  3105.         <#
  3106.             .SYNOPSIS
  3107.                 Determines whether or not a given path is a network location or a local drive.
  3108.            
  3109.             .DESCRIPTION
  3110.                 Function to determine whether or not a specified path is a local path, a UNC path,
  3111.                 or a mapped network drive.
  3112.  
  3113.             .PARAMETER Path
  3114.                 The path that we need to figure stuff out about,
  3115.         #>
  3116.    
  3117.         [CmdletBinding()]
  3118.         param(
  3119.             [Parameter(ValueFromPipeLine = $true)]
  3120.             [string]
  3121.             [ValidateNotNullOrEmpty()]
  3122.             $Path
  3123.         )
  3124.  
  3125.         $result = $false
  3126.    
  3127.         if ([bool]([URI]$Path).IsUNC) {
  3128.             $result = $true
  3129.         } else {
  3130.             $driveInfo = [IO.DriveInfo]((Resolve-Path $Path).Path)
  3131.  
  3132.             if ($driveInfo.DriveType -eq "Network") {
  3133.                 $result = $true
  3134.             }
  3135.         }
  3136.  
  3137.         return $result
  3138.     }
  3139.     ##########################################################################################
  3140.  
  3141.     #endregion Helper Functions
  3142. }
  3143.  
  3144. Process {
  3145.  
  3146.     $openWim      = $null
  3147.     $openVhd      = $null
  3148.     $openIso      = $null
  3149.     $openImage    = $null
  3150.     $vhdFinalName = $null
  3151.     $vhdFinalPath = $null
  3152.     $mountedHive  = $null
  3153.     $isoPath      = $null
  3154.  
  3155.     Write-Host $header
  3156.     try {
  3157.  
  3158.         # Create log folder
  3159.         if (Test-Path $logFolder) {
  3160.             $null = rd $logFolder -Force -Recurse
  3161.         }
  3162.  
  3163.         $null = md $logFolder -Force
  3164.  
  3165.         # Try to start transcripting.  If it's already running, we'll get an exception and swallow it.
  3166.         try {
  3167.             $null = Start-Transcript -Path (Join-Path $logFolder "Convert-WindowsImageTranscript.txt") -Force -ErrorAction SilentlyContinue
  3168.             $transcripting = $true
  3169.         } catch {
  3170.             Write-W2VWarn "Transcription is already running.  No Convert-WindowsImage-specific transcript will be created."
  3171.             $transcripting = $false
  3172.         }
  3173.  
  3174.         Add-Type -TypeDefinition $code -ReferencedAssemblies "System.Xml","System.Linq","System.Xml.Linq"
  3175.  
  3176.         # Check to make sure we're running as Admin.
  3177.         if (!(Test-Admin)) {
  3178.             throw "Images can only be applied by an administrator.  Please launch PowerShell elevated and run this script again."
  3179.         }
  3180.  
  3181.         # Check to make sure we're running on Win8.
  3182.         if (!(Test-WindowsVersion)) {
  3183.             throw "$scriptName requires Windows 8 Consumer Preview or higher.  Please use WIM2VHD.WSF (http://code.msdn.microsoft.com/wim2vhd) if you need to create VHDs from Windows 7."
  3184.         }
  3185.    
  3186.         # Resolve the path for the unattend file.
  3187.         if (![string]::IsNullOrEmpty($UnattendPath)) {
  3188.             $UnattendPath = (Resolve-Path $UnattendPath).Path
  3189.         }
  3190.  
  3191.         if ($ShowUI) {
  3192.        
  3193.             Write-W2VInfo "Launching UI..."
  3194.             Add-Type -AssemblyName System.Drawing,System.Windows.Forms
  3195.  
  3196.             #region Form Objects
  3197.             $frmMain                = New-Object System.Windows.Forms.Form
  3198.             $groupBox4              = New-Object System.Windows.Forms.GroupBox
  3199.             $btnGo                  = New-Object System.Windows.Forms.Button
  3200.             $groupBox3              = New-Object System.Windows.Forms.GroupBox
  3201.             $txtVhdName             = New-Object System.Windows.Forms.TextBox
  3202.             $label6                 = New-Object System.Windows.Forms.Label
  3203.             $btnWrkBrowse           = New-Object System.Windows.Forms.Button
  3204.             $cmbVhdSizeUnit         = New-Object System.Windows.Forms.ComboBox
  3205.             $numVhdSize             = New-Object System.Windows.Forms.NumericUpDown
  3206.             $cmbVhdFormat           = New-Object System.Windows.Forms.ComboBox
  3207.             $label5                 = New-Object System.Windows.Forms.Label
  3208.             $txtWorkingDirectory    = New-Object System.Windows.Forms.TextBox
  3209.             $cmbVhdType             = New-Object System.Windows.Forms.ComboBox
  3210.             $label4                 = New-Object System.Windows.Forms.Label
  3211.             $label3                 = New-Object System.Windows.Forms.Label
  3212.             $label2                 = New-Object System.Windows.Forms.Label
  3213.             $label7                 = New-Object System.Windows.Forms.Label
  3214.             $txtUnattendFile        = New-Object System.Windows.Forms.TextBox
  3215.             $btnUnattendBrowse      = New-Object System.Windows.Forms.Button
  3216.             $groupBox2              = New-Object System.Windows.Forms.GroupBox
  3217.             $cmbSkuList             = New-Object System.Windows.Forms.ComboBox
  3218.             $label1                 = New-Object System.Windows.Forms.Label
  3219.             $groupBox1              = New-Object System.Windows.Forms.GroupBox
  3220.             $txtSourcePath          = New-Object System.Windows.Forms.TextBox
  3221.             $btnBrowseWim           = New-Object System.Windows.Forms.Button
  3222.             $openFileDialog1        = New-Object System.Windows.Forms.OpenFileDialog
  3223.             $openFolderDialog1      = New-Object System.Windows.Forms.FolderBrowserDialog
  3224.             $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
  3225.  
  3226.             #endregion Form Objects
  3227.  
  3228.             #region Event scriptblocks.
  3229.  
  3230.             $btnGo_OnClick                          = {
  3231.                 $frmMain.Close()
  3232.             }
  3233.  
  3234.             $btnWrkBrowse_OnClick                   = {
  3235.                 $openFolderDialog1.RootFolder       = "Desktop"
  3236.                 $openFolderDialog1.Description      = "Select the folder you'd like your VHD(X) to be created in."
  3237.                 $openFolderDialog1.SelectedPath     = $WorkingDirectory
  3238.        
  3239.                 $ret = $openFolderDialog1.ShowDialog()
  3240.  
  3241.                 if ($ret -ilike "ok") {
  3242.                     $WorkingDirectory = $txtWorkingDirectory = $openFolderDialog1.SelectedPath
  3243.                     Write-W2VInfo "Selected Working Directory is $WorkingDirectory..."
  3244.                 }
  3245.             }
  3246.  
  3247.             $btnUnattendBrowse_OnClick              = {
  3248.                 $openFileDialog1.InitialDirectory   = $pwd
  3249.                 $openFileDialog1.Filter             = "XML files (*.xml)|*.XML|All files (*.*)|*.*"
  3250.                 $openFileDialog1.FilterIndex        = 1
  3251.                 $openFileDialog1.CheckFileExists    = $true
  3252.                 $openFileDialog1.CheckPathExists    = $true
  3253.                 $openFileDialog1.FileName           = $null
  3254.                 $openFileDialog1.ShowHelp           = $false
  3255.                 $openFileDialog1.Title              = "Select an unattend file..."
  3256.        
  3257.                 $ret = $openFileDialog1.ShowDialog()
  3258.  
  3259.                 if ($ret -ilike "ok") {
  3260.                     $UnattendPath = $txtUnattendFile.Text = $openFileDialog1.FileName
  3261.                 }
  3262.             }
  3263.  
  3264.             $btnBrowseWim_OnClick                   = {
  3265.                 $openFileDialog1.InitialDirectory   = $pwd
  3266.                 $openFileDialog1.Filter             = "All compatible files (*.ISO, *.WIM)|*.ISO;*.WIM|All files (*.*)|*.*"
  3267.                 $openFileDialog1.FilterIndex        = 1
  3268.                 $openFileDialog1.CheckFileExists    = $true
  3269.                 $openFileDialog1.CheckPathExists    = $true
  3270.                 $openFileDialog1.FileName           = $null
  3271.                 $openFileDialog1.ShowHelp           = $false
  3272.                 $openFileDialog1.Title              = "Select a source file..."
  3273.        
  3274.                 $ret = $openFileDialog1.ShowDialog()
  3275.  
  3276.                 if ($ret -ilike "ok") {
  3277.  
  3278.                     if (([IO.FileInfo]$openFileDialog1.FileName).Extension -ilike ".iso") {
  3279.                    
  3280.                         if (Test-IsNetworkLocation $openFileDialog1.FileName) {
  3281.                             Write-W2VInfo "Copying ISO $(Split-Path $openFileDialog1.FileName -Leaf) to temp folder..."
  3282.                             Write-W2VWarn "The UI may become non-responsive while this copy takes place..."                        
  3283.                             Copy-Item -Path $openFileDialog1.FileName -Destination $env:Temp -Force
  3284.                             $openFileDialog1.FileName = "$($env:Temp)\$(Split-Path $openFileDialog1.FileName -Leaf)"
  3285.                         }
  3286.                    
  3287.                         $txtSourcePath.Text = $isoPath = (Resolve-Path $openFileDialog1.FileName).Path
  3288.                         Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..."
  3289.                    
  3290.                         $openIso     = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru
  3291.                        
  3292.                         # Refresh the DiskImage object so we can get the real information about it.  I assume this is a bug.
  3293.                         $openIso     = Get-DiskImage -ImagePath $isoPath
  3294.                         $driveLetter = ($openIso | Get-Volume).DriveLetter
  3295.  
  3296.                         $script:SourcePath  = "$($driveLetter):\sources\install.wim"
  3297.  
  3298.                         # Check to see if there's a WIM file we can muck about with.
  3299.                         Write-W2VInfo "Looking for $($SourcePath)..."
  3300.                         if (!(Test-Path $SourcePath)) {
  3301.                             throw "The specified ISO does not appear to be valid Windows installation media."
  3302.                         }
  3303.                     } else {
  3304.                         $txtSourcePath.Text = $script:SourcePath = $openFileDialog1.FileName
  3305.                     }
  3306.  
  3307.                     # Check to see if the WIM is local, or on a network location.  If the latter, copy it locally.
  3308.                     if (Test-IsNetworkLocation $SourcePath) {
  3309.                         Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..."
  3310.                         Write-W2VWarn "The UI may become non-responsive while this copy takes place..."
  3311.                         Copy-Item -Path $SourcePath -Destination $env:Temp -Force
  3312.                         $txtSourcePath.Text = $script:SourcePath = "$($env:Temp)\$(Split-Path $SourcePath -Leaf)"
  3313.                     }
  3314.  
  3315.                     $script:SourcePath = (Resolve-Path $SourcePath).Path
  3316.  
  3317.                     Write-W2VInfo "Scanning WIM metadata..."
  3318.        
  3319.                     $tempOpenWim = $null
  3320.  
  3321.                     try {
  3322.  
  3323.                         $tempOpenWim   = New-Object WIM2VHD.WimFile $SourcePath
  3324.  
  3325.                         # Let's see if we're running against an unstaged build.  If we are, we need to blow up.
  3326.                         if ($tempOpenWim.ImageNames.Contains("Windows Longhorn Client") -or
  3327.                             $tempOpenWim.ImageNames.Contains("Windows Longhorn Server") -or
  3328.                             $tempOpenWim.ImageNames.Contains("Windows Longhorn Server Core")) {
  3329.                             [Windows.Forms.MessageBox]::Show(
  3330.                                 "Convert-WindowsImage cannot run against unstaged builds. Please try again with a staged build.",
  3331.                                 "WIM is incompatible!",
  3332.                                 "OK",
  3333.                                 "Error"
  3334.                             )
  3335.  
  3336.                             return
  3337.                         } else {
  3338.  
  3339.                             $tempOpenWim.Images | %{ $cmbSkuList.Items.Add($_.ImageFlags) }
  3340.                             $cmbSkuList.SelectedIndex = 0
  3341.                         }
  3342.  
  3343.                     } catch {
  3344.  
  3345.                         throw "Unable to load WIM metadata!"
  3346.                     } finally {
  3347.  
  3348.                         $tempOpenWim.Close()
  3349.                         Write-W2VTrace "Closing WIM metadata..."
  3350.                     }
  3351.                 }
  3352.             }
  3353.  
  3354.             $OnLoadForm_StateCorrection = {
  3355.  
  3356.                 # Correct the initial state of the form to prevent the .Net maximized form issue
  3357.                 $frmMain.WindowState      = $InitialFormWindowState
  3358.             }
  3359.  
  3360.             #endregion Event scriptblocks
  3361.  
  3362.             # Figure out VHD size and size unit.
  3363.             $unit = $null
  3364.             switch ([Math]::Round($SizeBytes.ToString().Length / 3)) {
  3365.                 3 { $unit = "MB"; break }
  3366.                 4 { $unit = "GB"; break }
  3367.                 5 { $unit = "TB"; break }
  3368.                 default { $unit = ""; break }
  3369.             }
  3370.  
  3371.             $quantity = Invoke-Expression -Command "$($SizeBytes) / 1$($unit)"
  3372.  
  3373.             #region Form Code
  3374.             #region frmMain
  3375.             $frmMain.DataBindings.DefaultDataSourceUpdateMode = 0
  3376.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3377.             $System_Drawing_Size.Height   = 579
  3378.             $System_Drawing_Size.Width    = 512
  3379.             $frmMain.ClientSize           = $System_Drawing_Size
  3380.             $frmMain.Font                 = New-Object System.Drawing.Font("Segoe UI",10,0,3,1)
  3381.             $frmMain.FormBorderStyle      = 1
  3382.             $frmMain.MaximizeBox          = $False
  3383.             $frmMain.MinimizeBox          = $False
  3384.             $frmMain.Name                 = "frmMain"
  3385.             $frmMain.StartPosition        = 1
  3386.             $frmMain.Text                 = "Convert-WindowsImage UI"
  3387.             #endregion frmMain
  3388.  
  3389.             #region groupBox4
  3390.             $groupBox4.DataBindings.DefaultDataSourceUpdateMode = 0
  3391.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3392.             $System_Drawing_Point.X       = 10
  3393.             $System_Drawing_Point.Y       = 498
  3394.             $groupBox4.Location           = $System_Drawing_Point
  3395.             $groupBox4.Name               = "groupBox4"
  3396.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3397.             $System_Drawing_Size.Height   = 69
  3398.             $System_Drawing_Size.Width    = 489
  3399.             $groupBox4.Size               = $System_Drawing_Size
  3400.             $groupBox4.TabIndex           = 8
  3401.             $groupBox4.TabStop            = $False
  3402.             $groupBox4.Text               = "4. Make the VHD!"
  3403.  
  3404.             $frmMain.Controls.Add($groupBox4)
  3405.             #endregion groupBox4
  3406.  
  3407.             #region btnGo
  3408.             $btnGo.DataBindings.DefaultDataSourceUpdateMode = 0
  3409.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3410.             $System_Drawing_Point.X       = 39
  3411.             $System_Drawing_Point.Y       = 24
  3412.             $btnGo.Location               = $System_Drawing_Point
  3413.             $btnGo.Name                   = "btnGo"
  3414.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3415.             $System_Drawing_Size.Height   = 33
  3416.             $System_Drawing_Size.Width    = 415
  3417.             $btnGo.Size                   = $System_Drawing_Size
  3418.             $btnGo.TabIndex               = 0
  3419.             $btnGo.Text                   = "&Make my VHD"
  3420.             $btnGo.UseVisualStyleBackColor = $True
  3421.             $btnGo.DialogResult           = "OK"
  3422.             $btnGo.add_Click($btnGo_OnClick)
  3423.  
  3424.             $groupBox4.Controls.Add($btnGo)
  3425.             $frmMain.AcceptButton = $btnGo
  3426.             #endregion btnGo
  3427.  
  3428.             #region groupBox3
  3429.             $groupBox3.DataBindings.DefaultDataSourceUpdateMode = 0
  3430.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3431.             $System_Drawing_Point.X       = 10
  3432.             $System_Drawing_Point.Y       = 243
  3433.             $groupBox3.Location           = $System_Drawing_Point
  3434.             $groupBox3.Name               = "groupBox3"
  3435.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3436.             $System_Drawing_Size.Height   = 245
  3437.             $System_Drawing_Size.Width    = 489
  3438.             $groupBox3.Size               = $System_Drawing_Size
  3439.             $groupBox3.TabIndex           = 7
  3440.             $groupBox3.TabStop            = $False
  3441.             $groupBox3.Text               = "3. Choose configuration options"
  3442.  
  3443.             $frmMain.Controls.Add($groupBox3)
  3444.             #endregion groupBox3
  3445.  
  3446.             #region txtVhdName
  3447.             $txtVhdName.DataBindings.DefaultDataSourceUpdateMode = 0
  3448.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3449.             $System_Drawing_Point.X       = 25
  3450.             $System_Drawing_Point.Y       = 150
  3451.             $txtVhdName.Location          = $System_Drawing_Point
  3452.             $txtVhdName.Name              = "txtVhdName"
  3453.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3454.             $System_Drawing_Size.Height   = 25
  3455.             $System_Drawing_Size.Width    = 418
  3456.             $txtVhdName.Size              = $System_Drawing_Size
  3457.             $txtVhdName.TabIndex          = 10
  3458.  
  3459.             $groupBox3.Controls.Add($txtVhdName)
  3460.             #endregion txtVhdName
  3461.  
  3462.             #region txtUnattendFile
  3463.             $txtUnattendFile.DataBindings.DefaultDataSourceUpdateMode = 0
  3464.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3465.             $System_Drawing_Point.X       = 25
  3466.             $System_Drawing_Point.Y       = 198
  3467.             $txtUnattendFile.Location     = $System_Drawing_Point
  3468.             $txtUnattendFile.Name         = "txtUnattendFile"
  3469.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3470.             $System_Drawing_Size.Height   = 25
  3471.             $System_Drawing_Size.Width    = 418
  3472.             $txtUnattendFile.Size         = $System_Drawing_Size
  3473.             $txtUnattendFile.TabIndex     = 11
  3474.  
  3475.             $groupBox3.Controls.Add($txtUnattendFile)
  3476.             #endregion txtUnattendFile
  3477.  
  3478.             #region label7
  3479.             $label7.DataBindings.DefaultDataSourceUpdateMode = 0
  3480.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3481.             $System_Drawing_Point.X       = 23
  3482.             $System_Drawing_Point.Y       = 180
  3483.             $label7.Location              = $System_Drawing_Point
  3484.             $label7.Name                  = "label7"
  3485.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3486.             $System_Drawing_Size.Height   = 23
  3487.             $System_Drawing_Size.Width    = 175
  3488.             $label7.Size                  = $System_Drawing_Size
  3489.             $label7.Text                  = "Unattend File (Optional)"
  3490.  
  3491.             $groupBox3.Controls.Add($label7)
  3492.             #endregion label7
  3493.  
  3494.             #region label6
  3495.             $label6.DataBindings.DefaultDataSourceUpdateMode = 0
  3496.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3497.             $System_Drawing_Point.X       = 23
  3498.             $System_Drawing_Point.Y       = 132
  3499.             $label6.Location              = $System_Drawing_Point
  3500.             $label6.Name                  = "label6"
  3501.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3502.             $System_Drawing_Size.Height   = 23
  3503.             $System_Drawing_Size.Width    = 175
  3504.             $label6.Size                  = $System_Drawing_Size
  3505.             $label6.Text                  = "VHD Name (Optional)"
  3506.  
  3507.             $groupBox3.Controls.Add($label6)
  3508.             #endregion label6
  3509.  
  3510.             #region btnUnattendBrowse
  3511.             $btnUnattendBrowse.DataBindings.DefaultDataSourceUpdateMode = 0
  3512.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3513.             $System_Drawing_Point.X       = 449
  3514.             $System_Drawing_Point.Y       = 199
  3515.             $btnUnattendBrowse.Location   = $System_Drawing_Point
  3516.             $btnUnattendBrowse.Name       = "btnUnattendBrowse"
  3517.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3518.             $System_Drawing_Size.Height   = 25
  3519.             $System_Drawing_Size.Width    = 27
  3520.             $btnUnattendBrowse.Size       = $System_Drawing_Size
  3521.             $btnUnattendBrowse.TabIndex   = 9
  3522.             $btnUnattendBrowse.Text       = "..."
  3523.             $btnUnattendBrowse.UseVisualStyleBackColor = $True
  3524.             $btnUnattendBrowse.add_Click($btnUnattendBrowse_OnClick)
  3525.    
  3526.             $groupBox3.Controls.Add($btnUnattendBrowse)
  3527.             #endregion btnUnattendBrowse
  3528.  
  3529.             #region btnWrkBrowse
  3530.             $btnWrkBrowse.DataBindings.DefaultDataSourceUpdateMode = 0
  3531.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3532.             $System_Drawing_Point.X       = 449
  3533.             $System_Drawing_Point.Y       = 98
  3534.             $btnWrkBrowse.Location        = $System_Drawing_Point
  3535.             $btnWrkBrowse.Name            = "btnWrkBrowse"
  3536.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3537.             $System_Drawing_Size.Height   = 25
  3538.             $System_Drawing_Size.Width    = 27
  3539.             $btnWrkBrowse.Size            = $System_Drawing_Size
  3540.             $btnWrkBrowse.TabIndex        = 9
  3541.             $btnWrkBrowse.Text            = "..."
  3542.             $btnWrkBrowse.UseVisualStyleBackColor = $True
  3543.             $btnWrkBrowse.add_Click($btnWrkBrowse_OnClick)
  3544.    
  3545.             $groupBox3.Controls.Add($btnWrkBrowse)
  3546.             #endregion btnWrkBrowse
  3547.  
  3548.             #region cmbVhdSizeUnit
  3549.             $cmbVhdSizeUnit.DataBindings.DefaultDataSourceUpdateMode = 0
  3550.             $cmbVhdSizeUnit.FormattingEnabled = $True
  3551.             $cmbVhdSizeUnit.Items.Add("MB") | Out-Null
  3552.             $cmbVhdSizeUnit.Items.Add("GB") | Out-Null
  3553.             $cmbVhdSizeUnit.Items.Add("TB") | Out-Null
  3554.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3555.             $System_Drawing_Point.X       = 409
  3556.             $System_Drawing_Point.Y       = 42
  3557.             $cmbVhdSizeUnit.Location      = $System_Drawing_Point
  3558.             $cmbVhdSizeUnit.Name          = "cmbVhdSizeUnit"
  3559.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3560.             $System_Drawing_Size.Height   = 25
  3561.             $System_Drawing_Size.Width    = 67
  3562.             $cmbVhdSizeUnit.Size          = $System_Drawing_Size
  3563.             $cmbVhdSizeUnit.TabIndex      = 5
  3564.             $cmbVhdSizeUnit.Text          = $unit
  3565.  
  3566.             $groupBox3.Controls.Add($cmbVhdSizeUnit)
  3567.             #endregion cmbVhdSizeUnit
  3568.  
  3569.             #region numVhdSize
  3570.             $numVhdSize.DataBindings.DefaultDataSourceUpdateMode = 0
  3571.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3572.             $System_Drawing_Point.X       = 340
  3573.             $System_Drawing_Point.Y       = 42
  3574.             $numVhdSize.Location          = $System_Drawing_Point
  3575.             $numVhdSize.Name              = "numVhdSize"
  3576.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3577.             $System_Drawing_Size.Height   = 25
  3578.             $System_Drawing_Size.Width    = 63
  3579.             $numVhdSize.Size              = $System_Drawing_Size
  3580.             $numVhdSize.TabIndex          = 4
  3581.             $numVhdSize.Value             = $quantity
  3582.  
  3583.             $groupBox3.Controls.Add($numVhdSize)
  3584.             #endregion numVhdSize
  3585.  
  3586.             #region cmbVhdFormat
  3587.             $cmbVhdFormat.DataBindings.DefaultDataSourceUpdateMode = 0
  3588.             $cmbVhdFormat.FormattingEnabled = $True
  3589.             $cmbVhdFormat.Items.Add("VHD")  | Out-Null
  3590.             $cmbVhdFormat.Items.Add("VHDX") | Out-Null
  3591.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3592.             $System_Drawing_Point.X       = 25
  3593.             $System_Drawing_Point.Y       = 42
  3594.             $cmbVhdFormat.Location        = $System_Drawing_Point
  3595.             $cmbVhdFormat.Name            = "cmbVhdFormat"
  3596.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3597.             $System_Drawing_Size.Height   = 25
  3598.             $System_Drawing_Size.Width    = 136
  3599.             $cmbVhdFormat.Size            = $System_Drawing_Size
  3600.             $cmbVhdFormat.TabIndex        = 0
  3601.             $cmbVhdFormat.Text            = $VHDFormat
  3602.  
  3603.             $groupBox3.Controls.Add($cmbVhdFormat)
  3604.             #endregion cmbVhdFormat
  3605.  
  3606.             #region label5
  3607.             $label5.DataBindings.DefaultDataSourceUpdateMode = 0
  3608.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3609.             $System_Drawing_Point.X       = 23
  3610.             $System_Drawing_Point.Y       = 76
  3611.             $label5.Location              = $System_Drawing_Point
  3612.             $label5.Name                  = "label5"
  3613.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3614.             $System_Drawing_Size.Height   = 23
  3615.             $System_Drawing_Size.Width    = 264
  3616.             $label5.Size                  = $System_Drawing_Size
  3617.             $label5.TabIndex              = 8
  3618.             $label5.Text                  = "Working Directory"
  3619.  
  3620.             $groupBox3.Controls.Add($label5)
  3621.             #endregion label5
  3622.  
  3623.             #region txtWorkingDirectory
  3624.             $txtWorkingDirectory.DataBindings.DefaultDataSourceUpdateMode = 0
  3625.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3626.             $System_Drawing_Point.X       = 25
  3627.             $System_Drawing_Point.Y       = 99
  3628.             $txtWorkingDirectory.Location = $System_Drawing_Point
  3629.             $txtWorkingDirectory.Name     = "txtWorkingDirectory"
  3630.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3631.             $System_Drawing_Size.Height   = 25
  3632.             $System_Drawing_Size.Width    = 418
  3633.             $txtWorkingDirectory.Size     = $System_Drawing_Size
  3634.             $txtWorkingDirectory.TabIndex = 7
  3635.             $txtWorkingDirectory.Text     = $WorkingDirectory
  3636.  
  3637.             $groupBox3.Controls.Add($txtWorkingDirectory)
  3638.             #endregion txtWorkingDirectory
  3639.  
  3640.             #region cmbVhdType
  3641.             $cmbVhdType.DataBindings.DefaultDataSourceUpdateMode = 0
  3642.             $cmbVhdType.FormattingEnabled = $True
  3643.             $cmbVhdType.Items.Add("Dynamic") | Out-Null
  3644.             $cmbVhdType.Items.Add("Fixed")   | Out-Null
  3645.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3646.             $System_Drawing_Point.X       = 176
  3647.             $System_Drawing_Point.Y       = 42
  3648.             $cmbVhdType.Location          = $System_Drawing_Point
  3649.             $cmbVhdType.Name              = "cmbVhdType"
  3650.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3651.             $System_Drawing_Size.Height   = 25
  3652.             $System_Drawing_Size.Width    = 144
  3653.             $cmbVhdType.Size              = $System_Drawing_Size
  3654.             $cmbVhdType.TabIndex          = 2
  3655.             $cmbVhdType.Text              = $VHDType
  3656.  
  3657.             $groupBox3.Controls.Add($cmbVhdType)
  3658.             #endregion cmbVhdType
  3659.  
  3660.             #region label4
  3661.             $label4.DataBindings.DefaultDataSourceUpdateMode = 0
  3662.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3663.             $System_Drawing_Point.X       = 340
  3664.             $System_Drawing_Point.Y       = 21
  3665.             $label4.Location              = $System_Drawing_Point
  3666.             $label4.Name                  = "label4"
  3667.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3668.             $System_Drawing_Size.Height   = 27
  3669.             $System_Drawing_Size.Width    = 86
  3670.             $label4.Size                  = $System_Drawing_Size
  3671.             $label4.TabIndex              = 6
  3672.             $label4.Text                  = "VHD Size"
  3673.  
  3674.             $groupBox3.Controls.Add($label4)
  3675.             #endregion label4
  3676.  
  3677.             #region label3
  3678.             $label3.DataBindings.DefaultDataSourceUpdateMode = 0
  3679.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3680.             $System_Drawing_Point.X       = 176
  3681.             $System_Drawing_Point.Y       = 21
  3682.             $label3.Location              = $System_Drawing_Point
  3683.             $label3.Name                  = "label3"
  3684.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3685.             $System_Drawing_Size.Height   = 27
  3686.             $System_Drawing_Size.Width    = 92
  3687.             $label3.Size                  = $System_Drawing_Size
  3688.             $label3.TabIndex              = 3
  3689.             $label3.Text                  = "VHD Type"
  3690.  
  3691.             $groupBox3.Controls.Add($label3)
  3692.             #endregion label3
  3693.  
  3694.             #region label2
  3695.             $label2.DataBindings.DefaultDataSourceUpdateMode = 0
  3696.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3697.             $System_Drawing_Point.X       = 25
  3698.             $System_Drawing_Point.Y       = 21
  3699.             $label2.Location              = $System_Drawing_Point
  3700.             $label2.Name                  = "label2"
  3701.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3702.             $System_Drawing_Size.Height   = 30
  3703.             $System_Drawing_Size.Width    = 118
  3704.             $label2.Size                  = $System_Drawing_Size
  3705.             $label2.TabIndex              = 1
  3706.             $label2.Text                  = "VHD Format"
  3707.  
  3708.             $groupBox3.Controls.Add($label2)
  3709.             #endregion label2
  3710.  
  3711.             #region groupBox2
  3712.             $groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0
  3713.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3714.             $System_Drawing_Point.X       = 10
  3715.             $System_Drawing_Point.Y       = 169
  3716.             $groupBox2.Location           = $System_Drawing_Point
  3717.             $groupBox2.Name               = "groupBox2"
  3718.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3719.             $System_Drawing_Size.Height   = 68
  3720.             $System_Drawing_Size.Width    = 490
  3721.             $groupBox2.Size               = $System_Drawing_Size
  3722.             $groupBox2.TabIndex           = 6
  3723.             $groupBox2.TabStop            = $False
  3724.             $groupBox2.Text               = "2. Choose a SKU from the list"
  3725.  
  3726.             $frmMain.Controls.Add($groupBox2)
  3727.             #endregion groupBox2
  3728.  
  3729.             #region cmbSkuList
  3730.             $cmbSkuList.DataBindings.DefaultDataSourceUpdateMode = 0
  3731.             $cmbSkuList.FormattingEnabled = $True
  3732.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3733.             $System_Drawing_Point.X       = 25
  3734.             $System_Drawing_Point.Y       = 24
  3735.             $cmbSkuList.Location          = $System_Drawing_Point
  3736.             $cmbSkuList.Name              = "cmbSkuList"
  3737.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3738.             $System_Drawing_Size.Height   = 25
  3739.             $System_Drawing_Size.Width    = 452
  3740.             $cmbSkuList.Size              = $System_Drawing_Size
  3741.             $cmbSkuList.TabIndex          = 2
  3742.  
  3743.             $groupBox2.Controls.Add($cmbSkuList)
  3744.             #endregion cmbSkuList
  3745.  
  3746.             #region label1
  3747.             $label1.DataBindings.DefaultDataSourceUpdateMode = 0
  3748.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3749.             $System_Drawing_Point.X       = 23
  3750.             $System_Drawing_Point.Y       = 21
  3751.             $label1.Location              = $System_Drawing_Point
  3752.             $label1.Name                  = "label1"
  3753.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3754.             $System_Drawing_Size.Height   = 71
  3755.             $System_Drawing_Size.Width    = 464
  3756.             $label1.Size                  = $System_Drawing_Size
  3757.             $label1.TabIndex              = 5
  3758.             $label1.Text                  = $uiHeader
  3759.  
  3760.             $frmMain.Controls.Add($label1)
  3761.             #endregion label1
  3762.  
  3763.             #region groupBox1
  3764.             $groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0
  3765.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3766.             $System_Drawing_Point.X       = 10
  3767.             $System_Drawing_Point.Y       = 95
  3768.             $groupBox1.Location           = $System_Drawing_Point
  3769.             $groupBox1.Name               = "groupBox1"
  3770.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3771.             $System_Drawing_Size.Height   = 68
  3772.             $System_Drawing_Size.Width    = 490
  3773.             $groupBox1.Size               = $System_Drawing_Size
  3774.             $groupBox1.TabIndex           = 4
  3775.             $groupBox1.TabStop            = $False
  3776.             $groupBox1.Text               = "1. Choose a source"
  3777.  
  3778.             $frmMain.Controls.Add($groupBox1)
  3779.             #endregion groupBox1
  3780.  
  3781.             #region txtSourcePath
  3782.             $txtSourcePath.DataBindings.DefaultDataSourceUpdateMode = 0
  3783.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3784.             $System_Drawing_Point.X       = 25
  3785.             $System_Drawing_Point.Y       = 24
  3786.             $txtSourcePath.Location       = $System_Drawing_Point
  3787.             $txtSourcePath.Name           = "txtSourcePath"
  3788.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3789.             $System_Drawing_Size.Height   = 25
  3790.             $System_Drawing_Size.Width    = 418
  3791.             $txtSourcePath.Size           = $System_Drawing_Size
  3792.             $txtSourcePath.TabIndex       = 0
  3793.  
  3794.             $groupBox1.Controls.Add($txtSourcePath)
  3795.             #endregion txtSourcePath
  3796.  
  3797.             #region btnBrowseWim
  3798.             $btnBrowseWim.DataBindings.DefaultDataSourceUpdateMode = 0
  3799.             $System_Drawing_Point         = New-Object System.Drawing.Point
  3800.             $System_Drawing_Point.X       = 449
  3801.             $System_Drawing_Point.Y       = 24
  3802.             $btnBrowseWim.Location        = $System_Drawing_Point
  3803.             $btnBrowseWim.Name            = "btnBrowseWim"
  3804.             $System_Drawing_Size          = New-Object System.Drawing.Size
  3805.             $System_Drawing_Size.Height   = 25
  3806.             $System_Drawing_Size.Width    = 28
  3807.             $btnBrowseWim.Size            = $System_Drawing_Size
  3808.             $btnBrowseWim.TabIndex        = 1
  3809.             $btnBrowseWim.Text            = "..."
  3810.             $btnBrowseWim.UseVisualStyleBackColor = $True
  3811.             $btnBrowseWim.add_Click($btnBrowseWim_OnClick)
  3812.  
  3813.             $groupBox1.Controls.Add($btnBrowseWim)
  3814.             #endregion btnBrowseWim
  3815.  
  3816.             $openFileDialog1.FileName     = "openFileDialog1"
  3817.             $openFileDialog1.ShowHelp     = $True
  3818.  
  3819.             #endregion Form Code
  3820.  
  3821.             # Save the initial state of the form
  3822.             $InitialFormWindowState       = $frmMain.WindowState
  3823.    
  3824.             # Init the OnLoad event to correct the initial state of the form
  3825.             $frmMain.add_Load($OnLoadForm_StateCorrection)
  3826.  
  3827.             # Return the constructed form.
  3828.             $ret = $frmMain.ShowDialog()
  3829.  
  3830.             if (!($ret -ilike "OK")) {
  3831.                 throw "Form session has been cancelled."
  3832.             }
  3833.  
  3834.             if ([string]::IsNullOrEmpty($SourcePath)) {
  3835.                 throw "No source path specified."
  3836.             }
  3837.  
  3838.             # VHD Format
  3839.             $VHDFormat        = $cmbVhdFormat.SelectedItem
  3840.  
  3841.             # VHD Size
  3842.             $SizeBytes        = Invoke-Expression "$($numVhdSize.Value)$($cmbVhdSizeUnit.SelectedItem)"
  3843.  
  3844.             # VHD Type
  3845.             $VHDType          = $cmbVhdType.SelectedItem
  3846.  
  3847.             # Working Directory
  3848.             $WorkingDirectory = $txtWorkingDirectory.Text
  3849.  
  3850.             # VHDPath
  3851.             if (![string]::IsNullOrEmpty($txtVhdName.Text)) {
  3852.                 $VHDPath      = "$($WorkingDirectory)\$($txtVhdName.Text)"
  3853.             }
  3854.  
  3855.             # Edition
  3856.             if (![string]::IsNullOrEmpty($cmbSkuList.SelectedItem)) {
  3857.                 $Edition      = $cmbSkuList.SelectedItem
  3858.             }
  3859.  
  3860.             # Because we used ShowDialog, we need to manually dispose of the form.
  3861.             # This probably won't make much of a difference, but let's free up all of the resources we can
  3862.             # before we start the conversion process.
  3863.  
  3864.             $frmMain.Dispose()
  3865.         }
  3866.  
  3867.         # There's a difference between the maximum sizes for VHDs and VHDXs.  Make sure we follow it.
  3868.         if ("VHD" -ilike $VHDFormat) {
  3869.             if ($SizeBytes -gt $vhdMaxSize) {
  3870.                 Write-W2VWarn "For the VHD file format, the maximum file size is ~2040GB.  We're automatically setting the size to 2040GB for you."
  3871.                 $SizeBytes = 2040GB
  3872.             }
  3873.         }
  3874.  
  3875.         # Check if -VHDPath and -WorkingDirectory were both specified.
  3876.         if ((![String]::IsNullOrEmpty($VHDPath)) -and (![String]::IsNullOrEmpty($WorkingDirectory))) {
  3877.             if ($WorkingDirectory -ne $pwd) {
  3878.                 # If the WorkingDirectory is anything besides $pwd, tell people that the WorkingDirectory is being ignored.
  3879.                 Write-W2VWarn "Specifying -VHDPath and -WorkingDirectory at the same time is contradictory."
  3880.                 Write-W2VWarn "Ignoring the WorkingDirectory specification."
  3881.                 $WorkingDirectory = Split-Path $VHDPath -Parent
  3882.             }
  3883.         }
  3884.  
  3885.         if ($VHDPath) {
  3886.             # Check to see if there's a conflict between the specified file extension and the VHDFormat being used.
  3887.             $ext = ([IO.FileInfo]$VHDPath).Extension
  3888.  
  3889.             if (!($ext -ilike ".$($VHDFormat)")) {
  3890.                 throw "There is a mismatch between the VHDPath file extension ($($ext.ToUpper())), and the VHDFormat (.$($VHDFormat)).  Please ensure that these match and try again."
  3891.             }
  3892.         }
  3893.  
  3894.         # Create a temporary name for the VHD(x).  We'll name it properly at the end of the script.
  3895.         if ([String]::IsNullOrEmpty($VHDPath)) {
  3896.             $VHDPath      = Join-Path $WorkingDirectory "$($sessionKey).$($VHDFormat.ToLower())"
  3897.         } else {
  3898.             # Since we can't do Resolve-Path against a file that doesn't exist, we need to get creative in determining
  3899.             # the full path that the user specified (or meant to specify if they gave us a relative path).
  3900.             # Check to see if the path has a root specified.  If it doesn't, use the working directory.
  3901.             if (![IO.Path]::IsPathRooted($VHDPath)){
  3902.                 $VHDPath  = Join-Path $WorkingDirectory $VHDPath
  3903.             }
  3904.  
  3905.             $vhdFinalName = Split-Path $VHDPath -Leaf
  3906.             $VHDPath      = Join-Path (Split-Path $VHDPath -Parent) "$($sessionKey).$($VHDFormat.ToLower())"
  3907.         }
  3908.  
  3909.         Write-W2VTrace "Temporary $VHDFormat path is : $VHDPath"
  3910.  
  3911.         # If we're using an ISO, mount it and get the path to the WIM file.
  3912.         if (([IO.FileInfo]$SourcePath).Extension -ilike ".ISO") {
  3913.  
  3914.             # If the ISO isn't local, copy it down so we don't have to worry about resource contention
  3915.             # or about network latency.
  3916.             if (Test-IsNetworkLocation $SourcePath) {
  3917.                 Write-W2VInfo "Copying ISO $(Split-Path $SourcePath -Leaf) to temp folder..."
  3918.                 Copy-Item -Path $SourcePath -Destination $env:Temp -Force
  3919.                 $SourcePath = "$($env:Temp)\$(Split-Path $SourcePath -Leaf)"
  3920.             }
  3921.  
  3922.             $isoPath = (Resolve-Path $SourcePath).Path
  3923.  
  3924.             Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..."
  3925.             $openIso     = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru
  3926.             # Refresh the DiskImage object so we can get the real information about it.  I assume this is a bug.
  3927.             $openIso     = Get-DiskImage -ImagePath $isoPath
  3928.             $driveLetter = ($openIso | Get-Volume).DriveLetter
  3929.  
  3930.             $SourcePath  = "$($driveLetter):\sources\install.wim"
  3931.  
  3932.             # Check to see if there's a WIM file we can muck about with.
  3933.             Write-W2VInfo "Looking for $($SourcePath)..."
  3934.             if (!(Test-Path $SourcePath)) {
  3935.                 throw "The specified ISO does not appear to be valid Windows installation media."
  3936.             }
  3937.         }
  3938.  
  3939.         # Check to see if the WIM is local, or on a network location.  If the latter, copy it locally.
  3940.         if (Test-IsNetworkLocation $SourcePath) {
  3941.             Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..."
  3942.             Copy-Item -Path $SourcePath -Destination $env:Temp -Force
  3943.             $SourcePath = "$($env:Temp)\$(Split-Path $SourcePath -Leaf)"
  3944.         }
  3945.  
  3946.         $SourcePath  = (Resolve-Path $SourcePath).Path
  3947.    
  3948.         # We're good.  Open the WIM container.
  3949.         $openWim     = New-Object WIM2VHD.WimFile $SourcePath
  3950.  
  3951.         # Let's see if we're running against an unstaged build.  If we are, we need to blow up.
  3952.         if ($openWim.ImageNames.Contains("Windows Longhorn Client") -or
  3953.             $openWim.ImageNames.Contains("Windows Longhorn Server") -or
  3954.             $openWim.ImageNames.Contains("Windows Longhorn Server Core")) {
  3955.             throw "Convert-WindowsImage cannot run against unstaged builds. Please try again with a staged build."
  3956.         }
  3957.  
  3958.         # If there's only one image in the WIM, just selected that.
  3959.         if ($openWim.Images.Count -eq 1) {
  3960.             $Edition   = $openWim.Images[0].ImageFlags
  3961.             $openImage = $openWim[$Edition]
  3962.         } else {
  3963.  
  3964.             if ([String]::IsNullOrEmpty($Edition)) {
  3965.                 Write-W2VError "You must specify an Edition or SKU index, since the WIM has more than one image."
  3966.                 Write-W2VError "Valid edition names are:"
  3967.                 $openWim.Images | %{ Write-W2VError "  $($_.ImageFlags)" }
  3968.                 throw
  3969.             }
  3970.  
  3971.             if ([Int32]::TryParse($Edition, [ref]$null)) {
  3972.                 $openImage = $openWim[[Int32]$Edition]    
  3973.             } else {
  3974.                 $openImage = $openWim[$Edition]
  3975.             }        
  3976.         }
  3977.    
  3978.         if ($null -eq $openImage) {
  3979.             Write-W2VError "The specified edition does not appear to exist in the specified WIM."
  3980.             Write-W2VError "Valid edition names are:"
  3981.             $openWim.Images | %{ Write-W2VError "  $($_.ImageFlags)" }
  3982.             throw
  3983.         }
  3984.  
  3985.         Write-W2VInfo "Image $($openImage.ImageIndex) selected ($($openImage.ImageFlags))..."
  3986.  
  3987.         # Check to make sure that the image we're applying is Windows 7 or greater.
  3988.         if ($openImage.ImageVersion -lt $lowestSupportedVersion) {
  3989.             throw "Convert-WindowsImage only supports Windows 7 and Windows 8 WIM files.  The specified image does not appear to contain one of those operating systems."
  3990.         }
  3991.  
  3992.         <#
  3993.             Create the VHD using the VirtDisk Win32 API.
  3994.             So, why not use the New-VHD cmdlet here?
  3995.        
  3996.             New-VHD depends on the Hyper-V Cmdlets, which aren't installed by default.
  3997.             Installing those cmdlets isn't a big deal, but they depend on the Hyper-V WMI
  3998.             APIs, which in turn depend on Hyper-V.  In order to prevent Convert-WindowsImage
  3999.             from being dependent on Hyper-V (and thus, x64 systems only), we're using the
  4000.             VirtDisk APIs directly.
  4001.         #>
  4002.         if ($VHDType -eq "Dynamic") {
  4003.             Write-W2VInfo "Creating sparse disk..."
  4004.             $openVhd = [WIM2VHD.VirtualHardDisk]::CreateSparseDisk(
  4005.                 $VHDFormat,
  4006.                 $VHDPath,
  4007.                 $SizeBytes,
  4008.                 $true
  4009.             )
  4010.         } else {
  4011.             Write-W2VInfo "Creating fixed disk..."
  4012.             $openVhd = [WIM2VHD.VirtualHardDisk]::CreateFixedDisk(
  4013.                 $VHDFormat,
  4014.                 $VHDPath,
  4015.                 $SizeBytes,
  4016.                 $true
  4017.             )
  4018.         }
  4019.  
  4020.         # Attach the VHD.
  4021.         Write-W2VInfo "Attaching $VHDFormat..."
  4022.         $openVhd.Attach()
  4023.  
  4024.         Initialize-Disk -Number $openVhd.DiskIndex -PartitionStyle MBR
  4025.         $disk      = Get-Disk -Number $openVhd.DiskIndex
  4026.  
  4027.         Write-W2VInfo "Disk initialized..."
  4028.  
  4029.         $partition = New-Partition -DiskNumber $openVhd.DiskIndex -Size $disk.LargestFreeExtent -MbrType IFS -IsActive
  4030.         Write-W2VInfo "Disk partitioned..."
  4031.    
  4032.         $volume    = Format-Volume -Partition $partition -FileSystem NTFS -Force -Confirm:$false
  4033.         Write-W2VInfo "Volume formatted..."
  4034.    
  4035.         $partition | Add-PartitionAccessPath -AssignDriveLetter
  4036.         $drive     = $(Get-Partition -Disk $disk).AccessPaths[0]
  4037.         Write-W2VInfo "Access path ($drive) has been assigned..."
  4038.  
  4039.         Write-W2VInfo "Applying image to $VHDFormat.  This could take a while..."
  4040.  
  4041.         $openImage.Apply($drive)
  4042.  
  4043.         if (![string]::IsNullOrEmpty($UnattendPath)) {
  4044.             Write-W2VInfo "Applying unattend file ($(Split-Path $UnattendPath -Leaf))..."
  4045.             Copy-Item -Path $UnattendPath -Destination (Join-Path $drive "unattend.xml") -Force
  4046.         }
  4047.  
  4048.         Write-W2VInfo "Signing disk..."
  4049.         $flagText | Out-File -FilePath (Join-Path $drive "Convert-WindowsImageInfo.txt") -Encoding Unicode -Force
  4050.  
  4051.         if ($openImage.ImageArchitecture -ne "ARM") {
  4052.  
  4053.             Write-W2VInfo "Image applied.  Making image bootable..."
  4054.  
  4055.             $bcdBootArgs = @(
  4056.                 "$($drive)Windows",    # Path to the \Windows on the VHD
  4057.                 "/s $drive",           # Specifies the volume letter of the drive to create the \BOOT folder on.
  4058.                 "/v"                   # Enabled verbose logging.
  4059.             )
  4060.  
  4061.             Run-Executable -Executable $BCDBoot -Arguments $bcdBootArgs
  4062.  
  4063.             Apply-BcdStoreChanges                     `
  4064.                 -BcdStoreFile    "$($drive)boot\bcd"  `
  4065.                 -PartitionStyle  $PARTITION_STYLE_MBR `
  4066.                 -DiskSignature   $disk.Signature      `
  4067.                 -PartitionOffset $partition.Offset    
  4068.  
  4069.             Write-W2VInfo "Drive is bootable.  Cleaning up..."
  4070.  
  4071.             # Are we turning the debugger on?
  4072.             if ($EnableDebugger -inotlike "None") {
  4073.                 Write-W2VInfo "Turning kernel debugging on in the $($VHDFormat)..."
  4074.                 Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
  4075.                     "/store $($drive)\boot\bcd",
  4076.                     "/set `{default`} debug on"
  4077.                 )
  4078.             }
  4079.            
  4080.             # Configure the specified debugging transport and other settings.
  4081.             switch ($EnableDebugger) {
  4082.                
  4083.                 "Serial" {
  4084.                     Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
  4085.                         "/store $($drive)\boot\bcd",
  4086.                         "/dbgsettings SERIAL",
  4087.                         "DEBUGPORT:$($ComPort.Value)",
  4088.                         "BAUDRATE:$($BaudRate.Value)"
  4089.                     )
  4090.                     break
  4091.                 }
  4092.                
  4093.                 "1394" {
  4094.                     Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
  4095.                         "/store $($drive)\boot\bcd",
  4096.                         "/dbgsettings 1394",
  4097.                         "CHANNEL:$($Channel.Value)"
  4098.                     )
  4099.                     break
  4100.                 }
  4101.                
  4102.                 "USB" {
  4103.                     Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
  4104.                         "/store $($drive)\boot\bcd",
  4105.                         "/dbgsettings USB",
  4106.                         "TARGETNAME:$($Target.Value)"
  4107.                     )
  4108.                     break
  4109.                 }
  4110.                
  4111.                 "Local" {
  4112.                     Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
  4113.                         "/store $($drive)\boot\bcd",
  4114.                         "/dbgsettings LOCAL"
  4115.                     )
  4116.                     break
  4117.                 }
  4118.              
  4119.                 "Network" {
  4120.                     Run-Executable -Executable "BCDEDIT.EXE" -Arguments (
  4121.                         "/store $($drive)\boot\bcd",
  4122.                         "/dbgsettings NET",
  4123.                         "HOSTIP:$($IP.Value)",
  4124.                         "PORT:$($Port.Value)",
  4125.                         "KEY:$($Key.Value)"
  4126.                     )
  4127.                     break
  4128.                 }
  4129.                                
  4130.                 default {
  4131.                     # Nothing to do here - bail out.
  4132.                     break
  4133.                 }
  4134.             }
  4135.            
  4136.         } else {
  4137.             # Don't bother to check on debugging.  We can't boot WoA VHDs in VMs, and
  4138.             # if we're native booting, the changes need to be made to the BCD store on the
  4139.             # physical computer's boot volume.
  4140.            
  4141.             Write-W2VInfo "Not making VHD bootable, since WOA can't boot in VMs."
  4142.         }
  4143.  
  4144.         if ([String]::IsNullOrEmpty($vhdFinalName)) {
  4145.             # We need to generate a file name.
  4146.             Write-W2VInfo "Generating name for $($VHDFormat)..."
  4147.             $hive         = Mount-RegistryHive -Hive (Join-Path $drive "Windows\System32\Config\Software")
  4148.  
  4149.             $buildLabEx   = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").BuildLabEx
  4150.             $installType  = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").InstallationType
  4151.             $editionId    = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").EditionID
  4152.             $skuFamily    = $null
  4153.  
  4154.             Dismount-RegistryHive -HiveMountPoint $hive
  4155.  
  4156.             # Is this ServerCore?
  4157.             # Since we're only doing this string comparison against the InstallType key, we won't get
  4158.             # false positives with the Core SKU.
  4159.             if ($installType.ToUpper().Contains("CORE")) {
  4160.                 $editionId += "Core"
  4161.             }
  4162.  
  4163.             # What type of SKU are we?
  4164.             if ($installType.ToUpper().Contains("SERVER")) {
  4165.                 $skuFamily = "Server"
  4166.             } elseif ($installType.ToUpper().Contains("CLIENT")) {
  4167.                 $skuFamily = "Client"
  4168.             } else {
  4169.                 $skuFamily = "Unknown"
  4170.             }
  4171.  
  4172.             $vhdFinalName = "$($buildLabEx)_$($skuFamily)_$($editionId)_$($openImage.ImageDefaultLanguage).$($VHDFormat.ToLower())"
  4173.             Write-W2VTrace "$VHDFormat final name is : $vhdFinalName"
  4174.         }
  4175.  
  4176.         Write-W2VInfo "Closing $VHDFormat..."
  4177.         $openVhd.Close()
  4178.         $openVhd = $null
  4179.  
  4180.         $vhdFinalPath = Join-Path (Split-Path $VHDPath -Parent) $vhdFinalName
  4181.    
  4182.         if (Test-Path $vhdFinalPath) {
  4183.             Write-W2VInfo "Deleting pre-existing $VHDFormat : $(Split-Path $vhdFinalPath -Leaf)..."
  4184.             Remove-Item -Path $vhdFinalPath -Force
  4185.         }
  4186.    
  4187.         Rename-Item -Path (Resolve-Path $VHDPath).Path -NewName $vhdFinalName -Force
  4188.  
  4189.     } catch {
  4190.    
  4191.         Write-W2VError $_
  4192.         Write-W2VInfo "Log folder is $logFolder"
  4193.  
  4194.     } finally {
  4195.  
  4196.         # If we still have a WIM image open, close it.
  4197.         if ($openWim -ne $null) {
  4198.             Write-W2VInfo "Closing Windows image..."
  4199.             $openWim.Close()
  4200.         }
  4201.  
  4202.         # If we still have a registry hive mounted, dismount it.
  4203.         if ($mountedHive -ne $null) {
  4204.             Write-W2VInfo "Closing registry hive..."
  4205.             Dismount-RegistryHive -HiveMountPoint $mountedHive
  4206.         }
  4207.  
  4208.         # If we still have a VHD(X) open, close it.
  4209.         if ($openVhd -ne $null) {
  4210.             Write-W2VInfo "Closing $VHDFormat..."
  4211.             $openVhd.Close()
  4212.         }
  4213.  
  4214.         # If we still have an ISO open, close it.
  4215.         if ($openIso -ne $null) {
  4216.             Write-W2VInfo "Closing ISO..."
  4217.             Dismount-DiskImage $ISOPath
  4218.         }
  4219.    
  4220.         # Close out the transcript and tell the user we're done.
  4221.         Write-W2VInfo "Done."
  4222.         if ($transcripting) {
  4223.             $null = Stop-Transcript
  4224.         }
  4225.     }
  4226. }
  4227.  
  4228. End {
  4229.  
  4230.     if (($Passthru) -and (![string]::IsNullOrEmpty($vhdFinalPath)) -and (Test-Path $vhdFinalPath)) {
  4231.    
  4232.         return (Get-ChildItem -Path $vhdFinalPath)
  4233.     }
  4234. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement