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