diff --git a/Add-VMGpuPartitionAdapterFiles.psm1 b/Add-VMGpuPartitionAdapterFiles.psm1 deleted file mode 100644 index 488ebb1..0000000 --- a/Add-VMGpuPartitionAdapterFiles.psm1 +++ /dev/null @@ -1,77 +0,0 @@ -Function Add-VMGpuPartitionAdapterFiles { -param( -[string]$hostname = $ENV:COMPUTERNAME, -[string]$DriveLetter, -[string]$GPUName -) - -If (!($DriveLetter -like "*:*")) { - $DriveLetter = $Driveletter + ":" - } - -If ($GPUName -eq "AUTO") { - $PartitionableGPUList = Get-WmiObject -Class "Msvm_PartitionableGpu" -ComputerName $env:COMPUTERNAME -Namespace "ROOT\virtualization\v2" - $DevicePathName = $PartitionableGPUList.Name | Select-Object -First 1 - $GPU = Get-PnpDevice | Where-Object {($_.DeviceID -like "*$($DevicePathName.Substring(8,16))*") -and ($_.Status -eq "OK")} | Select-Object -First 1 - $GPUName = $GPU.Friendlyname - $GPUServiceName = $GPU.Service - } -Else { - $GPU = Get-PnpDevice | Where-Object {($_.Name -eq "$GPUName") -and ($_.Status -eq "OK")} | Select-Object -First 1 - $GPUServiceName = $GPU.Service - } -# Get Third Party drivers used, that are not provided by Microsoft and presumably included in the OS - -Write-Host "INFO : Finding and copying driver files for $GPUName to VM. This could take a while..." - -$Drivers = Get-WmiObject Win32_PNPSignedDriver | where {$_.DeviceName -eq "$GPUName"} - -New-Item -ItemType Directory -Path "$DriveLetter\windows\system32\HostDriverStore" -Force | Out-Null - -#copy directory associated with sys file -$servicePath = (Get-WmiObject Win32_SystemDriver | Where-Object {$_.Name -eq "$GPUServiceName"}).Pathname - $ServiceDriverDir = $servicepath.split('\')[0..5] -join('\') - $ServicedriverDest = ("$driveletter" + "\" + $($servicepath.split('\')[1..5] -join('\'))).Replace("DriverStore","HostDriverStore") - if (!(Test-Path $ServicedriverDest)) { - Copy-item -path "$ServiceDriverDir" -Destination "$ServicedriverDest" -Recurse - } - -# Initialize the list of detected driver packages as an array -$DriverFolders = @() -foreach ($d in $drivers) { - - $DriverFiles = @() - $ModifiedDeviceID = $d.DeviceID -replace "\\", "\\" - $Antecedent = "\\" + $hostname + "\ROOT\cimv2:Win32_PNPSignedDriver.DeviceID=""$ModifiedDeviceID""" - $DriverFiles += Get-WmiObject Win32_PNPSignedDriverCIMDataFile | where {$_.Antecedent -eq $Antecedent} - $DriverName = $d.DeviceName - $DriverID = $d.DeviceID - if ($DriverName -like "NVIDIA*") { - New-Item -ItemType Directory -Path "$driveletter\Windows\System32\drivers\Nvidia Corporation\" -Force | Out-Null - } - foreach ($i in $DriverFiles) { - $path = $i.Dependent.Split("=")[1] -replace '\\\\', '\' - $path2 = $path.Substring(1,$path.Length-2) - $InfItem = Get-Item -Path $path2 - $Version = $InfItem.VersionInfo.FileVersion - If ($path2 -like "c:\windows\system32\driverstore\*") { - $DriverDir = $path2.split('\')[0..5] -join('\') - $driverDest = ("$driveletter" + "\" + $($path2.split('\')[1..5] -join('\'))).Replace("driverstore","HostDriverStore") - if (!(Test-Path $driverDest)) { - Copy-item -path "$DriverDir" -Destination "$driverDest" -Recurse - } - } - Else { - $ParseDestination = $path2.Replace("c:", "$driveletter") - $Destination = $ParseDestination.Substring(0, $ParseDestination.LastIndexOf('\')) - if (!$(Test-Path -Path $Destination)) { - New-Item -ItemType Directory -Path $Destination -Force | Out-Null - } - Copy-Item $path2 -Destination $Destination -Force - - } - - } - } - -} \ No newline at end of file diff --git a/CopyFilesToVM.ps1 b/CopyFilesToVM.ps1 deleted file mode 100644 index b24df3a..0000000 --- a/CopyFilesToVM.ps1 +++ /dev/null @@ -1,4407 +0,0 @@ -$params = @{ - VMName = "GPUPV" - SourcePath = "C:\Users\james\Downloads\Win11_English_x64.iso" - Edition = 6 - VhdFormat = "VHDX" - DiskLayout = "UEFI" - SizeBytes = 40GB - MemoryAmount = 8GB - CPUCores = 4 - NetworkSwitch = "Default Switch" - VHDPath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\" - UnattendPath = "$PSScriptRoot"+"\autounattend.xml" - GPUName = "AUTO" - GPUResourceAllocationPercentage = 50 - Team_ID = "" - Key = "" - Username = "GPUVM" - Password = "CoolestPassword!" - Autologon = "true" -} - -Import-Module $PSSCriptRoot\Add-VMGpuPartitionAdapterFiles.psm1 - -function Is-Administrator -{ - $CurrentUser = [Security.Principal.WindowsIdentity]::GetCurrent(); - (New-Object Security.Principal.WindowsPrincipal $CurrentUser).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) -} - -Function Dismount-ISO { -param ( -[string]$SourcePath -) -$disk = Get-Volume | Where-Object {$_.DriveType -eq "CD-ROM"} | select * -Foreach ($d in $disk) { - Dismount-DiskImage -ImagePath $sourcePath | Out-Null - } -} - -Function Mount-ISOReliable { -param ( -[string]$SourcePath -) -$mountResult = Mount-DiskImage -ImagePath $SourcePath -$delay = 0 -Do { - if ($delay -gt 15) { - Function Get-NewDriveLetter { - $UsedDriveLetters = ((Get-Volume).DriveLetter) -join "" - Do { - $DriveLetter = (65..90)| Get-Random | % {[char]$_} - } - Until (!$UsedDriveLetters.Contains("$DriveLetter")) - $DriveLetter - } - $DriveLetter = "$(Get-NewDriveLetter)" + ":" - Get-WmiObject -Class Win32_volume | Where-Object {$_.Label -eq "CCCOMA_X64FRE_EN-US_DV9"} | Set-WmiInstance -Arguments @{DriveLetter="$driveletter"} - } - Start-Sleep -s 1 - $delay++ - } -Until (($mountResult | Get-Volume).DriveLetter -ne $NULL) -($mountResult | Get-Volume).DriveLetter -} - - -Function ConcatenateVHDPath { -param( -[string]$VHDPath, -[string]$VMName -) -if ($VHDPath[-1] -eq '\') { - $VHDPath + $VMName + ".vhdx" - } -Else { - $VHDPath + "\" + $VMName + ".vhdx" - } -} - -Function SmartExit { -param ( -[switch]$NoHalt, -[string]$ExitReason -) -if (($host.name -eq 'Windows PowerShell ISE Host') -or ($host.Name -eq 'Visual Studio Code Host')) { - Write-Host $ExitReason - Exit - } -else{ - if ($NoHalt) { - Write-Host $ExitReason - Exit - } - else { - Write-Host $ExitReason - Read-host -Prompt "Press any key to Exit..." - Exit - } - } -} - -Function Check-Params { - -$ExitReason = @() - -if ([ENVIRONMENT]::Is64BitProcess -eq $false) { - $ExitReason += "You are not using the correct version of Powershell, do not use Powershell(x86)." - } -if ((Is-Administrator) -eq $false) { - $ExitReason += "Script not running as Administrator, please run script as Administrator." - } -if (!(Test-Path $params.VHDPath)) { - $ExitReason += "VHDPath Directory doesn't exist, please create it before running this script." - } -if (!(test-path $params.SourcePath)) { - $ExitReason += "ISO Path Invalid. Please enter a valid ISO Path in the SourcePath section of Params." - } -else { - $ISODriveLetter = Mount-ISOReliable -SourcePath $params.SourcePath - if (!(Test-Path $("$ISODriveLetter"+":\Sources\install.wim"))) { - $ExitReason += "This ISO is invalid, please check readme for ISO downloading instructions." - } - Dismount-ISO -SourcePath $params.SourcePath - } -if ($params.Username -eq $params.VMName ) { - $ExitReason += "Username cannot be the same as VMName." - } -if (!($params.Username -match "^[a-zA-Z0-9]+$")) { - $ExitReason += "Username cannot contain special characters." - } -if (($params.VMName -notmatch "^[a-zA-Z0-9]+$") -or ($params.VMName.Length -gt 15)) { - $ExitReason += "VMName cannot contain special characters, or be more than 15 characters long" - } -if (([Environment]::OSVersion.Version.Build -lt 22000) -and ($params.GPUName -ne "AUTO")) { - $ExitReason += "GPUName must be set to AUTO on Windows 10." - } -If ($ExitReason.Count -gt 0) { - Write-Host "Script failed params check due to the following reasons:" -ForegroundColor DarkYellow - ForEach ($IndividualReason in $ExitReason) { - Write-Host "ERROR: $IndividualReason" -ForegroundColor RED - } - SmartExit - } -} - -Function Setup-ParsecInstall { -param( -[string]$DriveLetter, -[string]$Team_ID, -[string]$Key -) - $new = @() - - $content = get-content "$PSScriptRoot\user\psscripts.ini" - - foreach ($line in $content) { - if ($line -like "0Parameters="){ - $line = "0Parameters=$Team_ID $Key" - $new += $line - } - Else { - $new += $line - } - } - Set-Content -Value $new -Path "$PSScriptRoot\user\psscripts.ini" - if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon -ItemType directory | Out-Null} - if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logoff) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logoff -ItemType directory | Out-Null} - if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup -ItemType directory | Out-Null} - if((Test-Path -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Shutdown) -eq $true) {} Else {New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Shutdown -ItemType directory | Out-Null} - if((Test-Path -Path $DriveLetter\ProgramData\Easy-GPU-P) -eq $true) {} Else {New-Item -Path $DriveLetter\ProgramData\Easy-GPU-P -ItemType directory | Out-Null} - Copy-Item -Path $psscriptroot\VMScripts\VDDMonitor.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P - Copy-Item -Path $psscriptroot\VMScripts\VBCableInstall.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P - Copy-Item -Path $psscriptroot\VMScripts\ParsecVDDInstall.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P - Copy-Item -Path $psscriptroot\VMScripts\ParsecPublic.cer -Destination $DriveLetter\ProgramData\Easy-GPU-P - Copy-Item -Path $psscriptroot\VMScripts\Parsec.lnk -Destination $DriveLetter\ProgramData\Easy-GPU-P - Copy-Item -Path $psscriptroot\gpt.ini -Destination $DriveLetter\Windows\system32\GroupPolicy - Copy-Item -Path $psscriptroot\User\psscripts.ini -Destination $DriveLetter\Windows\system32\GroupPolicy\User\Scripts - Copy-Item -Path $psscriptroot\User\Install.ps1 -Destination $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon - Copy-Item -Path $psscriptroot\Machine\psscripts.ini -Destination $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts - Copy-Item -Path $psscriptroot\Machine\Install.ps1 -Destination $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup -} - -function Convert-WindowsImage { - <# - .NOTES - Copyright (c) Microsoft Corporation. All rights reserved. - - Use of this sample source code is subject to the terms of the Microsoft - license agreement under which you licensed this sample source code. If - you did not accept the terms of the license agreement, you are not - authorized to use this sample source code. For the terms of the license, - please see the license agreement between you and Microsoft or, if applicable, - see the LICENSE.RTF on your install media or the root of your tools installation. - THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES. - - .SYNOPSIS - Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media. - - .DESCRIPTION - Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media. - - .PARAMETER SourcePath - The complete path to the WIM or ISO file that will be converted to a Virtual Hard Disk. - The ISO file must be valid Windows installation media to be recognized successfully. - - .PARAMETER CacheSource - If the source WIM/ISO was copied locally, we delete it by default. - Pass $true to cache the source image from the temp directory. - - .PARAMETER VHDPath - The name and path of the Virtual Hard Disk to create. - Omitting this parameter will create the Virtual Hard Disk is the current directory, (or, - if specified by the -WorkingDirectory parameter, the working directory) and will automatically - name the file in the following format: - - ....___. - i.e.: - 9200.0.amd64fre.winmain_win8rtm.120725-1247_client_professional_en-us.vhd(x) - - .PARAMETER WorkingDirectory - Specifies the directory where the VHD(X) file should be generated. - If specified along with -VHDPath, the -WorkingDirectory value is ignored. - The default value is the current directory ($pwd). - - .PARAMETER TempDirectory - Specifies the directory where the logs and ISO files should be placed. - The default value is the temp directory ($env:Temp). - - .PARAMETER SizeBytes - The size of the Virtual Hard Disk to create. - For fixed disks, the VHD(X) file will be allocated all of this space immediately. - For dynamic disks, this will be the maximum size that the VHD(X) can grow to. - The default value is 40GB. - - .PARAMETER VHDFormat - Specifies whether to create a VHD or VHDX formatted Virtual Hard Disk. - The default is AUTO, which will create a VHD if using the BIOS disk layout or - VHDX if using UEFI or WindowsToGo layouts. - - .PARAMETER DiskLayout - Specifies whether to build the image for BIOS (MBR), UEFI (GPT), or WindowsToGo (MBR). - Generation 1 VMs require BIOS (MBR) images. Generation 2 VMs require UEFI (GPT) images. - Windows To Go images will boot in UEFI or BIOS but are not technically supported (upgrade - doesn't work) - - .PARAMETER UnattendPath - The complete path to an unattend.xml file that can be injected into the VHD(X). - - .PARAMETER Edition - The name or image index of the image to apply from the WIM. - - .PARAMETER Passthru - Specifies that the full path to the VHD(X) that is created should be - returned on the pipeline. - - .PARAMETER BCDBoot - By default, the version of BCDBOOT.EXE that is present in \Windows\System32 - is used by Convert-WindowsImage. If you need to specify an alternate version, - use this parameter to do so. - - .PARAMETER MergeFolder - Specifies additional MergeFolder path to be added to the root of the VHD(X) - - .PARAMETER BCDinVHD - Specifies the purpose of the VHD(x). Use NativeBoot to skip cration of BCD store - inside the VHD(x). Use VirtualMachine (or do not specify this option) to ensure - the BCD store is created inside the VHD(x). - - .PARAMETER Driver - Full path to driver(s) (.inf files) to inject to the OS inside the VHD(x). - - .PARAMETER ExpandOnNativeBoot - Specifies whether to expand the VHD(x) to its maximum suze upon native boot. - The default is True. Set to False to disable expansion. - - .PARAMETER RemoteDesktopEnable - Enable Remote Desktop to connect to the OS inside the VHD(x) upon provisioning. - Does not include Windows Firewall rules (firewall exceptions). The default is False. - - .PARAMETER Feature - Enables specified Windows Feature(s). Note that you need to specify the Internal names - understood by DISM and DISM CMDLets (e.g. NetFx3) instead of the "Friendly" names - from Server Manager CMDLets (e.g. NET-Framework-Core). - - .PARAMETER Package - Injects specified Windows Package(s). Accepts path to either a directory or individual - CAB or MSU file. - - .PARAMETER ShowUI - Specifies that the Graphical User Interface should be displayed. - - .PARAMETER EnableDebugger - Configures kernel debugging for the VHD(X) being created. - EnableDebugger takes a single argument which specifies the debugging transport to use. - Valid transports are: None, Serial, 1394, USB, Network, Local. - - Depending on the type of transport selected, additional configuration parameters will become - available. - - Serial: - -ComPort - The COM port number to use while communicating with the debugger. - The default value is 1 (indicating COM1). - -BaudRate - The baud rate (in bps) to use while communicating with the debugger. - The default value is 115200, valid values are: - 9600, 19200, 38400, 56700, 115200 - - 1394: - -Channel - The 1394 channel used to communicate with the debugger. - The default value is 10. - - USB: - -Target - The target name used for USB debugging. - The default value is "debugging". - - Network: - -IPAddress - The IP address of the debugging host computer. - -Port - The port on which to connect to the debugging host. - The default value is 50000, with a minimum value of 49152. - -Key - The key used to encrypt the connection. Only [0-9] and [a-z] are allowed. - -nodhcp - Prevents the use of DHCP to obtain the target IP address. - -newkey - Specifies that a new encryption key should be generated for the connection. - - .PARAMETER DismPath - Full Path to an alternative version of the Dism.exe tool. The default is the current OS version. - - .PARAMETER ApplyEA - Specifies that any EAs captured in the WIM should be applied to the VHD. - The default is False. - - .EXAMPLE - .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -WorkingDirectory D:\foo - - This command will create a 40GB dynamically expanding VHD in the D:\foo folder. - The VHD will be based on the Professional edition from D:\foo\install.wim, - and will be named automatically. - - .EXAMPLE - .\Convert-WindowsImage.ps1 -SourcePath D:\foo\Win7SP1.iso -Edition Ultimate -VHDPath D:\foo\Win7_Ultimate_SP1.vhd - - This command will parse the ISO file D:\foo\Win7SP1.iso and try to locate - \sources\install.wim. If that file is found, it will be used to create a - dynamically-expanding 40GB VHD containing the Ultimate SKU, and will be - named D:\foo\Win7_Ultimate_SP1.vhd - - .EXAMPLE - .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -EnableDebugger Serial -ComPort 2 -BaudRate 38400 - - This command will create a VHD from D:\foo\install.wim of the Professional SKU. - Serial debugging will be enabled in the VHD via COM2 at a baud rate of 38400bps. - - .OUTPUTS - System.IO.FileInfo - #> - [CmdletBinding(DefaultParameterSetName="SRC", - HelpURI="https://github.com/Microsoft/Virtualization-Documentation/tree/master/hyperv-tools/Convert-WindowsImage")] - - param( - [Parameter(ParameterSetName="SRC", Mandatory=$true, ValueFromPipeline=$true)] - [Alias("WIM")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateScript({ Test-Path $(Resolve-Path $_) })] - $SourcePath, - - [Parameter(ParameterSetName="SRC")] - [Alias("DriveLetter")] - [string] - [ValidateNotNullOrEmpty()] - [string]$ISODriveLetter, - - [Parameter(ParameterSetName="SRC")] - [Alias("GPU")] - [string] - [ValidateNotNullOrEmpty()] - [string]$GPUName, - - [Parameter(ParameterSetName="SRC")] - [Alias("TeamID")] - [string] - #[ValidateNotNullOrEmpty()] - [string]$Team_ID, - - [Parameter(ParameterSetName="SRC")] - [Alias("Teamkey")] - [string] - #[ValidateNotNullOrEmpty()] - [string]$Key, - - [Parameter(ParameterSetName="SRC")] - [switch] - $CacheSource = $false, - - [Parameter(ParameterSetName="SRC")] - [Alias("SKU")] - [string[]] - [ValidateNotNullOrEmpty()] - $Edition, - - [Parameter(ParameterSetName="SRC")] - [Alias("WorkDir")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateScript({ Test-Path $_ })] - $WorkingDirectory = $pwd, - - [Parameter(ParameterSetName="SRC")] - [Alias("TempDir")] - [string] - [ValidateNotNullOrEmpty()] - $TempDirectory = $env:Temp, - - [Parameter(ParameterSetName="SRC")] - [Alias("VHD")] - [string] - [ValidateNotNullOrEmpty()] - $VHDPath, - - [Parameter(ParameterSetName="SRC")] - [Alias("Size")] - [UInt64] - [ValidateNotNullOrEmpty()] - [ValidateRange(512MB, 64TB)] - $SizeBytes = 25GB, - - [Parameter(ParameterSetName="SRC")] - [Alias("Format")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateSet("VHD", "VHDX", "AUTO")] - $VHDFormat = "AUTO", - - [Parameter(ParameterSetName="SRC")] - [Alias("MergeFolder")] - [string] - [ValidateNotNullOrEmpty()] - $MergeFolderPath = "", - - [Parameter(ParameterSetName="SRC", Mandatory=$true)] - [Alias("Layout")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateSet("BIOS", "UEFI", "WindowsToGo")] - $DiskLayout, - - [Parameter(ParameterSetName="SRC")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateSet("NativeBoot", "VirtualMachine")] - $BCDinVHD = "VirtualMachine", - - [Parameter(ParameterSetName="SRC")] - [Parameter(ParameterSetName="UI")] - [string] - $BCDBoot = "bcdboot.exe", - - [Parameter(ParameterSetName="SRC")] - [Parameter(ParameterSetName="UI")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateSet("None", "Serial", "1394", "USB", "Local", "Network")] - $EnableDebugger = "None", - - [Parameter(ParameterSetName="SRC")] - [string[]] - [ValidateNotNullOrEmpty()] - $Feature, - - [Parameter(ParameterSetName="SRC")] - [string[]] - [ValidateNotNullOrEmpty()] - [ValidateScript({ Test-Path $(Resolve-Path $_) })] - $Driver, - - [Parameter(ParameterSetName="SRC")] - [string[]] - [ValidateNotNullOrEmpty()] - [ValidateScript({ Test-Path $(Resolve-Path $_) })] - $Package, - - [Parameter(ParameterSetName="SRC")] - [switch] - $ExpandOnNativeBoot = $true, - - [Parameter(ParameterSetName="SRC")] - [switch] - $RemoteDesktopEnable = $false, - - [Parameter(ParameterSetName="SRC")] - [Alias("Unattend")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateScript({ Test-Path $(Resolve-Path $_) })] - $UnattendPath, - - [Parameter(ParameterSetName="SRC")] - [Parameter(ParameterSetName="UI")] - [switch] - $Passthru, - - [Parameter(ParameterSetName="SRC")] - [string] - [ValidateNotNullOrEmpty()] - [ValidateScript({ Test-Path $(Resolve-Path $_) })] - $DismPath, - - [Parameter(ParameterSetName="SRC")] - [switch] - $ApplyEA = $false, - - [Parameter(ParameterSetName="UI")] - [switch] - $ShowUI - ) - #region Code - - # Begin Dynamic Parameters - # Create the parameters for the various types of debugging. - DynamicParam - { - #Set-StrictMode -version 3 - - # Set up the dynamic parameters. - # Dynamic parameters are only available if certain conditions are met, so they'll only show up - # as valid parameters when those conditions apply. Here, the conditions are based on the value of - # the EnableDebugger parameter. Depending on which of a set of values is the specified argument - # for EnableDebugger, different parameters will light up, as outlined below. - - $parameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary - - if (!(Test-Path Variable:Private:EnableDebugger)) - { - return $parameterDictionary - } - - switch ($EnableDebugger) - { - "Serial" - { - #region ComPort - - $ComPortAttr = New-Object System.Management.Automation.ParameterAttribute - $ComPortAttr.ParameterSetName = "__AllParameterSets" - $ComPortAttr.Mandatory = $false - - $ComPortValidator = New-Object System.Management.Automation.ValidateRangeAttribute( - 1, - 10 # Is that a good maximum? - ) - - $ComPortNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $ComPortAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $ComPortAttrCollection.Add($ComPortAttr) - $ComPortAttrCollection.Add($ComPortValidator) - $ComPortAttrCollection.Add($ComPortNotNull) - - $ComPort = New-Object System.Management.Automation.RuntimeDefinedParameter( - "ComPort", - [UInt16], - $ComPortAttrCollection - ) - - # By default, use COM1 - $ComPort.Value = 1 - $parameterDictionary.Add("ComPort", $ComPort) - #endregion ComPort - - #region BaudRate - $BaudRateAttr = New-Object System.Management.Automation.ParameterAttribute - $BaudRateAttr.ParameterSetName = "__AllParameterSets" - $BaudRateAttr.Mandatory = $false - - $BaudRateValidator = New-Object System.Management.Automation.ValidateSetAttribute( - 9600, 19200,38400, 57600, 115200 - ) - - $BaudRateNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $BaudRateAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $BaudRateAttrCollection.Add($BaudRateAttr) - $BaudRateAttrCollection.Add($BaudRateValidator) - $BaudRateAttrCollection.Add($BaudRateNotNull) - - $BaudRate = New-Object System.Management.Automation.RuntimeDefinedParameter( - "BaudRate", - [UInt32], - $BaudRateAttrCollection - ) - - # By default, use 115,200. - $BaudRate.Value = 115200 - $parameterDictionary.Add("BaudRate", $BaudRate) - #endregion BaudRate - - break - } - - "1394" - { - $ChannelAttr = New-Object System.Management.Automation.ParameterAttribute - $ChannelAttr.ParameterSetName = "__AllParameterSets" - $ChannelAttr.Mandatory = $false - - $ChannelValidator = New-Object System.Management.Automation.ValidateRangeAttribute( - 0, - 62 - ) - - $ChannelNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $ChannelAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $ChannelAttrCollection.Add($ChannelAttr) - $ChannelAttrCollection.Add($ChannelValidator) - $ChannelAttrCollection.Add($ChannelNotNull) - - $Channel = New-Object System.Management.Automation.RuntimeDefinedParameter( - "Channel", - [UInt16], - $ChannelAttrCollection - ) - - # By default, use channel 10 - $Channel.Value = 10 - $parameterDictionary.Add("Channel", $Channel) - break - } - - "USB" - { - $TargetAttr = New-Object System.Management.Automation.ParameterAttribute - $TargetAttr.ParameterSetName = "__AllParameterSets" - $TargetAttr.Mandatory = $false - - $TargetNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $TargetAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $TargetAttrCollection.Add($TargetAttr) - $TargetAttrCollection.Add($TargetNotNull) - - $Target = New-Object System.Management.Automation.RuntimeDefinedParameter( - "Target", - [string], - $TargetAttrCollection - ) - - # By default, use target = "debugging" - $Target.Value = "Debugging" - $parameterDictionary.Add("Target", $Target) - break - } - - "Network" - { - #region IP - $IpAttr = New-Object System.Management.Automation.ParameterAttribute - $IpAttr.ParameterSetName = "__AllParameterSets" - $IpAttr.Mandatory = $true - - $IpValidator = New-Object System.Management.Automation.ValidatePatternAttribute( - "\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" - ) - $IpNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $IpAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $IpAttrCollection.Add($IpAttr) - $IpAttrCollection.Add($IpValidator) - $IpAttrCollection.Add($IpNotNull) - - $IP = New-Object System.Management.Automation.RuntimeDefinedParameter( - "IPAddress", - [string], - $IpAttrCollection - ) - - # There's no good way to set a default value for this. - $parameterDictionary.Add("IPAddress", $IP) - #endregion IP - - #region Port - $PortAttr = New-Object System.Management.Automation.ParameterAttribute - $PortAttr.ParameterSetName = "__AllParameterSets" - $PortAttr.Mandatory = $false - - $PortValidator = New-Object System.Management.Automation.ValidateRangeAttribute( - 49152, - 50039 - ) - - $PortNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $PortAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $PortAttrCollection.Add($PortAttr) - $PortAttrCollection.Add($PortValidator) - $PortAttrCollection.Add($PortNotNull) - - - $Port = New-Object System.Management.Automation.RuntimeDefinedParameter( - "Port", - [UInt16], - $PortAttrCollection - ) - - # By default, use port 50000 - $Port.Value = 50000 - $parameterDictionary.Add("Port", $Port) - #endregion Port - - #region Key - $KeyAttr = New-Object System.Management.Automation.ParameterAttribute - $KeyAttr.ParameterSetName = "__AllParameterSets" - $KeyAttr.Mandatory = $true - - $KeyValidator = New-Object System.Management.Automation.ValidatePatternAttribute( - "\b([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+)\b" - ) - - $KeyNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute - - $KeyAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $KeyAttrCollection.Add($KeyAttr) - $KeyAttrCollection.Add($KeyValidator) - $KeyAttrCollection.Add($KeyNotNull) - - $Key = New-Object System.Management.Automation.RuntimeDefinedParameter( - "Key", - [string], - $KeyAttrCollection - ) - - # Don't set a default key. - $parameterDictionary.Add("Key", $Key) - #endregion Key - - #region NoDHCP - $NoDHCPAttr = New-Object System.Management.Automation.ParameterAttribute - $NoDHCPAttr.ParameterSetName = "__AllParameterSets" - $NoDHCPAttr.Mandatory = $false - - $NoDHCPAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $NoDHCPAttrCollection.Add($NoDHCPAttr) - - $NoDHCP = New-Object System.Management.Automation.RuntimeDefinedParameter( - "NoDHCP", - [switch], - $NoDHCPAttrCollection - ) - - $parameterDictionary.Add("NoDHCP", $NoDHCP) - #endregion NoDHCP - - #region NewKey - $NewKeyAttr = New-Object System.Management.Automation.ParameterAttribute - $NewKeyAttr.ParameterSetName = "__AllParameterSets" - $NewKeyAttr.Mandatory = $false - - $NewKeyAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] - $NewKeyAttrCollection.Add($NewKeyAttr) - - $NewKey = New-Object System.Management.Automation.RuntimeDefinedParameter( - "NewKey", - [switch], - $NewKeyAttrCollection - ) - - # Don't set a default key. - $parameterDictionary.Add("NewKey", $NewKey) - #endregion NewKey - - break - } - - # There's nothing to do for local debugging. - # Synthetic debugging is not yet implemented. - - default - { - break - } - } - - return $parameterDictionary - } - - Begin - { - ########################################################################################## - # Constants and Pseudo-Constants - ########################################################################################## - $PARTITION_STYLE_MBR = 0x00000000 # The default value - $PARTITION_STYLE_GPT = 0x00000001 # Just in case... - - # Version information that can be populated by timebuild. - $ScriptVersion = DATA - { - ConvertFrom-StringData -StringData @" - Major = 10 - Minor = 0 - Build = 14278 - Qfe = 1000 - Branch = rs1_es_media - Timestamp = 160201-1707 - Flavor = amd64fre -"@ -} - - $myVersion = "$($ScriptVersion.Major).$($ScriptVersion.Minor).$($ScriptVersion.Build).$($ScriptVersion.QFE).$($ScriptVersion.Flavor).$($ScriptVersion.Branch).$($ScriptVersion.Timestamp)" - $scriptName = "Convert-WindowsImage" # Name of the script, obviously. - $sessionKey = [Guid]::NewGuid().ToString() # Session key, used for keeping records unique between multiple runs. - $logFolder = "$($TempDirectory)\$($scriptName)\$($sessionKey)" # Log folder path. - $vhdMaxSize = 2040GB # Maximum size for VHD is ~2040GB. - $vhdxMaxSize = 64TB # Maximum size for VHDX is ~64TB. - $lowestSupportedVersion = New-Object Version "6.1" # The lowest supported *image* version; making sure we don't run against Vista/2k8. - $lowestSupportedBuild = 9200 # The lowest supported *host* build. Set to Win8 CP. - $transcripting = $false - - # Since we use the VHDFormat in output, make it uppercase. - # We'll make it lowercase again when we use it as a file extension. - $VHDFormat = $VHDFormat.ToUpper() - ########################################################################################## - # Here Strings - ########################################################################################## - - # Banner text displayed during each run. - $header = @" - -Windows(R) Image to Virtual Hard Disk Converter for Windows(R) 10 -Copyright (C) Microsoft Corporation. All rights reserved. -Version $myVersion - -"@ - - # Text used as the banner in the UI. - $uiHeader = @" -You can use the fields below to configure the VHD or VHDX that you want to create! -"@ - - #region Helper Functions - - ########################################################################################## - # Helper Functions - ########################################################################################## - - <# - Functions to mount and dismount registry hives. - These hives will automatically be accessible via the HKLM:\ registry PSDrive. - - It should be noted that I have more confidence in using the RegLoadKey and - RegUnloadKey Win32 APIs than I do using REG.EXE - it just seems like we should - do things ourselves if we can, instead of using yet another binary. - - Consider this a TODO for future versions. - #> - Function Mount-RegistryHive - { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] - [System.IO.FileInfo] - [ValidateNotNullOrEmpty()] - [ValidateScript({ $_.Exists })] - $Hive - ) - - $mountKey = [System.Guid]::NewGuid().ToString() - $regPath = "REG.EXE" - - if (Test-Path HKLM:\$mountKey) - { - throw "The registry path already exists. I should just regenerate it, but I'm lazy." - } - - $regArgs = ( - "LOAD", - "HKLM\$mountKey", - $Hive.Fullname - ) - try - { - - Run-Executable -Executable $regPath -Arguments $regArgs - - } - catch - { - throw - } - - # Set a global variable containing the name of the mounted registry key - # so we can unmount it if there's an error. - $global:mountedHive = $mountKey - - return $mountKey - } - - ########################################################################################## - - Function Dismount-RegistryHive - { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] - [string] - [ValidateNotNullOrEmpty()] - $HiveMountPoint - ) - - $regPath = "REG.EXE" - - $regArgs = ( - "UNLOAD", - "HKLM\$($HiveMountPoint)" - ) - - Run-Executable -Executable $regPath -Arguments $regArgs - - $global:mountedHive = $null - } - - ########################################################################################## - - function - Test-Admin - { - <# - .SYNOPSIS - Short function to determine whether the logged-on user is an administrator. - - .EXAMPLE - Do you honestly need one? There are no parameters! - - .OUTPUTS - $true if user is admin. - $false if user is not an admin. - #> - [CmdletBinding()] - param() - - $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent()) - $isAdmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) - Write-W2VTrace "isUserAdmin? $isAdmin" - - return $isAdmin - } - - ########################################################################################## - - function - Get-WindowsBuildNumber - { - $os = Get-WmiObject -Class Win32_OperatingSystem - return [int]($os.BuildNumber) - } - - ########################################################################################## - - function - Test-WindowsVersion - { - $isWin8 = ((Get-WindowsBuildNumber) -ge [int]$lowestSupportedBuild) - - Write-W2VTrace "is Windows 8 or Higher? $isWin8" - return $isWin8 - } - - ########################################################################################## - - function - Write-W2VInfo - { - # Function to make the Write-Host output a bit prettier. - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [string] - [ValidateNotNullOrEmpty()] - $text - ) - Write-Host "INFO : $($text)" - } - - ########################################################################################## - - function - Write-W2VTrace - { - # Function to make the Write-Verbose output... well... exactly the same as it was before. - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [string] - [ValidateNotNullOrEmpty()] - $text - ) - Write-Verbose $text - } - - ########################################################################################## - - function - Write-W2VError - { - # Function to make the Write-Host (NOT Write-Error) output prettier in the case of an error. - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [string] - [ValidateNotNullOrEmpty()] - $text - ) - Write-Host "ERROR : $($text)" - } - - ########################################################################################## - - function - Write-W2VWarn - { - # Function to make the Write-Host (NOT Write-Warning) output prettier. - [CmdletBinding()] - param( - [Parameter(Mandatory = $true, ValueFromPipeline = $true)] - [string] - [ValidateNotNullOrEmpty()] - $text - ) - Write-Host "WARN : $($text)" -ForegroundColor (Get-Host).PrivateData.WarningForegroundColor - } - - ########################################################################################## - - function - Run-Executable - { - <# - .SYNOPSIS - Runs an external executable file, and validates the error level. - - .PARAMETER Executable - The path to the executable to run and monitor. - - .PARAMETER Arguments - An array of arguments to pass to the executable when it's executed. - - .PARAMETER SuccessfulErrorCode - The error code that means the executable ran successfully. - The default value is 0. - #> - - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string] - [ValidateNotNullOrEmpty()] - $Executable, - - [Parameter(Mandatory=$true)] - [string[]] - [ValidateNotNullOrEmpty()] - $Arguments, - - [Parameter()] - [int] - [ValidateNotNullOrEmpty()] - $SuccessfulErrorCode = 0 - - ) - - Write-W2VTrace "Running $Executable $Arguments" - $ret = Start-Process ` - -FilePath $Executable ` - -ArgumentList $Arguments ` - -NoNewWindow ` - -Wait ` - -RedirectStandardOutput "$($TempDirectory)\$($scriptName)\$($sessionKey)\$($Executable)-StandardOutput.txt" ` - -RedirectStandardError "$($TempDirectory)\$($scriptName)\$($sessionKey)\$($Executable)-StandardError.txt" ` - -Passthru - - Write-W2VTrace "Return code was $($ret.ExitCode)." - - if ($ret.ExitCode -ne $SuccessfulErrorCode) - { - throw "$Executable failed with code $($ret.ExitCode)!" - } - } - - ########################################################################################## - Function Test-IsNetworkLocation - { - <# - .SYNOPSIS - Determines whether or not a given path is a network location or a local drive. - - .DESCRIPTION - Function to determine whether or not a specified path is a local path, a UNC path, - or a mapped network drive. - - .PARAMETER Path - The path that we need to figure stuff out about, - #> - - [CmdletBinding()] - param( - [Parameter(ValueFromPipeLine = $true)] - [string] - [ValidateNotNullOrEmpty()] - $Path - ) - - $result = $false - - if ([bool]([URI]$Path).IsUNC) - { - $result = $true - } - else - { - $driveInfo = [IO.DriveInfo]((Resolve-Path $Path).Path) - - if ($driveInfo.DriveType -eq "Network") - { - $result = $true - } - } - - return $result - } - ########################################################################################## - - #endregion Helper Functions - } - - Process - { - Write-Host $header - - $disk = $null - $openWim = $null - $openIso = $null - $openImage = $null - $vhdFinalName = $null - $vhdFinalPath = $null - $mountedHive = $null - $isoPath = $null - $tempSource = $null - - if (Get-Command Get-WindowsOptionalFeature -ErrorAction SilentlyContinue) - { - try - { - $hyperVEnabled = $((Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V).State -eq "Enabled") - } - catch - { - # WinPE DISM does not support online queries. This will throw on non-WinPE machines - $winpeVersion = (Get-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\WinPE').Version - - Write-W2VInfo "Running WinPE version $winpeVersion" - - $hyperVEnabled = $false - } - } - else - { - $hyperVEnabled = $false - } - - $vhd = @() - - try - { - # Create log folder - if (Test-Path $logFolder) - { - $null = rd $logFolder -Force -Recurse - } - - $null = md $logFolder -Force - - # Try to start transcripting. If it's already running, we'll get an exception and swallow it. - try - { - $null = Start-Transcript -Path (Join-Path $logFolder "Convert-WindowsImageTranscript.txt") -Force -ErrorAction SilentlyContinue - $transcripting = $true - } - catch - { - Write-W2VWarn "Transcription is already running. No Convert-WindowsImage-specific transcript will be created." - $transcripting = $false - } - - # - # Add types - # - Add-WindowsImageTypes - - # Check to make sure we're running as Admin. - if (!(Test-Admin)) - { - throw "Images can only be applied by an administrator. Please launch PowerShell elevated and run this script again." - } - - # Check to make sure we're running on Win8. - if (!(Test-WindowsVersion)) - { - 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." - } - - # Resolve the path for the unattend file. - if (![string]::IsNullOrEmpty($UnattendPath)) - { - $UnattendPath = (Resolve-Path $UnattendPath).Path - } - - if ($ShowUI) - { - - Write-W2VInfo "Launching UI..." - Add-Type -AssemblyName System.Drawing,System.Windows.Forms - - #region Form Objects - $frmMain = New-Object System.Windows.Forms.Form - $groupBox4 = New-Object System.Windows.Forms.GroupBox - $btnGo = New-Object System.Windows.Forms.Button - $groupBox3 = New-Object System.Windows.Forms.GroupBox - $txtVhdName = New-Object System.Windows.Forms.TextBox - $label6 = New-Object System.Windows.Forms.Label - $btnWrkBrowse = New-Object System.Windows.Forms.Button - $cmbVhdSizeUnit = New-Object System.Windows.Forms.ComboBox - $numVhdSize = New-Object System.Windows.Forms.NumericUpDown - $cmbVhdFormat = New-Object System.Windows.Forms.ComboBox - $label5 = New-Object System.Windows.Forms.Label - $txtWorkingDirectory = New-Object System.Windows.Forms.TextBox - $label4 = New-Object System.Windows.Forms.Label - $label3 = New-Object System.Windows.Forms.Label - $label2 = New-Object System.Windows.Forms.Label - $label7 = New-Object System.Windows.Forms.Label - $txtUnattendFile = New-Object System.Windows.Forms.TextBox - $btnUnattendBrowse = New-Object System.Windows.Forms.Button - $groupBox2 = New-Object System.Windows.Forms.GroupBox - $cmbSkuList = New-Object System.Windows.Forms.ComboBox - $label1 = New-Object System.Windows.Forms.Label - $groupBox1 = New-Object System.Windows.Forms.GroupBox - $txtSourcePath = New-Object System.Windows.Forms.TextBox - $btnBrowseWim = New-Object System.Windows.Forms.Button - $openFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog - $openFolderDialog1 = New-Object System.Windows.Forms.FolderBrowserDialog - $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState - - #endregion Form Objects - - #region Event scriptblocks. - - $btnGo_OnClick = { - $frmMain.Close() - } - - $btnWrkBrowse_OnClick = { - $openFolderDialog1.RootFolder = "Desktop" - $openFolderDialog1.Description = "Select the folder you'd like your VHD(X) to be created in." - $openFolderDialog1.SelectedPath = $WorkingDirectory - - $ret = $openFolderDialog1.ShowDialog() - - if ($ret -ilike "ok") - { - $WorkingDirectory = $txtWorkingDirectory = $openFolderDialog1.SelectedPath - Write-W2VInfo "Selected Working Directory is $WorkingDirectory..." - } - } - - $btnUnattendBrowse_OnClick = { - $openFileDialog1.InitialDirectory = $pwd - $openFileDialog1.Filter = "XML files (*.xml)|*.XML|All files (*.*)|*.*" - $openFileDialog1.FilterIndex = 1 - $openFileDialog1.CheckFileExists = $true - $openFileDialog1.CheckPathExists = $true - $openFileDialog1.FileName = $null - $openFileDialog1.ShowHelp = $false - $openFileDialog1.Title = "Select an unattend file..." - - $ret = $openFileDialog1.ShowDialog() - - if ($ret -ilike "ok") - { - $UnattendPath = $txtUnattendFile.Text = $openFileDialog1.FileName - } - } - - $btnBrowseWim_OnClick = { - $openFileDialog1.InitialDirectory = $pwd - $openFileDialog1.Filter = "All compatible files (*.ISO, *.WIM)|*.ISO;*.WIM|All files (*.*)|*.*" - $openFileDialog1.FilterIndex = 1 - $openFileDialog1.CheckFileExists = $true - $openFileDialog1.CheckPathExists = $true - $openFileDialog1.FileName = $null - $openFileDialog1.ShowHelp = $false - $openFileDialog1.Title = "Select a source file..." - - $ret = $openFileDialog1.ShowDialog() - - if ($ret -ilike "ok") - { - - if (([IO.FileInfo]$openFileDialog1.FileName).Extension -ilike ".iso") - { - - if (Test-IsNetworkLocation $openFileDialog1.FileName) - { - Write-W2VInfo "Copying ISO $(Split-Path $openFileDialog1.FileName -Leaf) to temp folder..." - Write-W2VWarn "The UI may become non-responsive while this copy takes place..." - Copy-Item -Path $openFileDialog1.FileName -Destination $TempDirectory -Force - $openFileDialog1.FileName = "$($TempDirectory)\$(Split-Path $openFileDialog1.FileName -Leaf)" - } - - $txtSourcePath.Text = $isoPath = (Resolve-Path $openFileDialog1.FileName).Path - Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..." - - $script:SourcePath = "$($driveLetter):\sources\install.wim" - - # Check to see if there's a WIM file we can muck about with. - Write-W2VInfo "Looking for $($SourcePath)..." - if (!(Test-Path $SourcePath)) - { - throw "The specified ISO does not appear to be valid Windows installation media." - } - } - else - { - $txtSourcePath.Text = $script:SourcePath = $openFileDialog1.FileName - } - - # Check to see if the WIM is local, or on a network location. If the latter, copy it locally. - if (Test-IsNetworkLocation $SourcePath) - { - Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..." - Write-W2VWarn "The UI may become non-responsive while this copy takes place..." - Copy-Item -Path $SourcePath -Destination $TempDirectory -Force - $txtSourcePath.Text = $script:SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)" - } - - $script:SourcePath = (Resolve-Path $SourcePath).Path - - Write-W2VInfo "Scanning WIM metadata..." - - $tempOpenWim = $null - - try - { - $tempOpenWim = New-Object WIM2VHD.WimFile $SourcePath - - # Let's see if we're running against an unstaged build. If we are, we need to blow up. - if ($tempOpenWim.ImageNames.Contains("Windows Longhorn Client") -or - $tempOpenWim.ImageNames.Contains("Windows Longhorn Server") -or - $tempOpenWim.ImageNames.Contains("Windows Longhorn Server Core")) - { - [Windows.Forms.MessageBox]::Show( - "Convert-WindowsImage cannot run against unstaged builds. Please try again with a staged build.", - "WIM is incompatible!", - "OK", - "Error" - ) - - return - } - else - { - $tempOpenWim.Images | %{ $cmbSkuList.Items.Add($_.ImageFlags) } - $cmbSkuList.SelectedIndex = 0 - } - - } - catch - { - throw "Unable to load WIM metadata!" - } - finally - { - $tempOpenWim.Close() - Write-W2VTrace "Closing WIM metadata..." - } - } - } - - $OnLoadForm_StateCorrection = { - - # Correct the initial state of the form to prevent the .Net maximized form issue - $frmMain.WindowState = $InitialFormWindowState - } - - #endregion Event scriptblocks - - # Figure out VHD size and size unit. - $unit = $null - switch ([Math]::Round($SizeBytes.ToString().Length / 3)) - { - 3 { $unit = "MB"; break } - 4 { $unit = "GB"; break } - 5 { $unit = "TB"; break } - default { $unit = ""; break } - } - - $quantity = Invoke-Expression -Command "$($SizeBytes) / 1$($unit)" - - #region Form Code - #region frmMain - $frmMain.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 579 - $System_Drawing_Size.Width = 512 - $frmMain.ClientSize = $System_Drawing_Size - $frmMain.Font = New-Object System.Drawing.Font("Segoe UI",10,0,3,1) - $frmMain.FormBorderStyle = 1 - $frmMain.MaximizeBox = $False - $frmMain.MinimizeBox = $False - $frmMain.Name = "frmMain" - $frmMain.StartPosition = 1 - $frmMain.Text = "Convert-WindowsImage UI" - #endregion frmMain - - #region groupBox4 - $groupBox4.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 10 - $System_Drawing_Point.Y = 498 - $groupBox4.Location = $System_Drawing_Point - $groupBox4.Name = "groupBox4" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 69 - $System_Drawing_Size.Width = 489 - $groupBox4.Size = $System_Drawing_Size - $groupBox4.TabIndex = 8 - $groupBox4.TabStop = $False - $groupBox4.Text = "4. Make the VHD!" - - $frmMain.Controls.Add($groupBox4) - #endregion groupBox4 - - #region btnGo - $btnGo.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 39 - $System_Drawing_Point.Y = 24 - $btnGo.Location = $System_Drawing_Point - $btnGo.Name = "btnGo" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 33 - $System_Drawing_Size.Width = 415 - $btnGo.Size = $System_Drawing_Size - $btnGo.TabIndex = 0 - $btnGo.Text = "&Make my VHD" - $btnGo.UseVisualStyleBackColor = $True - $btnGo.DialogResult = "OK" - $btnGo.add_Click($btnGo_OnClick) - - $groupBox4.Controls.Add($btnGo) - $frmMain.AcceptButton = $btnGo - #endregion btnGo - - #region groupBox3 - $groupBox3.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 10 - $System_Drawing_Point.Y = 243 - $groupBox3.Location = $System_Drawing_Point - $groupBox3.Name = "groupBox3" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 245 - $System_Drawing_Size.Width = 489 - $groupBox3.Size = $System_Drawing_Size - $groupBox3.TabIndex = 7 - $groupBox3.TabStop = $False - $groupBox3.Text = "3. Choose configuration options" - - $frmMain.Controls.Add($groupBox3) - #endregion groupBox3 - - #region txtVhdName - $txtVhdName.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 150 - $txtVhdName.Location = $System_Drawing_Point - $txtVhdName.Name = "txtVhdName" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 418 - $txtVhdName.Size = $System_Drawing_Size - $txtVhdName.TabIndex = 10 - - $groupBox3.Controls.Add($txtVhdName) - #endregion txtVhdName - - #region txtUnattendFile - $txtUnattendFile.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 198 - $txtUnattendFile.Location = $System_Drawing_Point - $txtUnattendFile.Name = "txtUnattendFile" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 418 - $txtUnattendFile.Size = $System_Drawing_Size - $txtUnattendFile.TabIndex = 11 - - $groupBox3.Controls.Add($txtUnattendFile) - #endregion txtUnattendFile - - #region label7 - $label7.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 23 - $System_Drawing_Point.Y = 180 - $label7.Location = $System_Drawing_Point - $label7.Name = "label7" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 23 - $System_Drawing_Size.Width = 175 - $label7.Size = $System_Drawing_Size - $label7.Text = "Unattend File (Optional)" - - $groupBox3.Controls.Add($label7) - #endregion label7 - - #region label6 - $label6.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 23 - $System_Drawing_Point.Y = 132 - $label6.Location = $System_Drawing_Point - $label6.Name = "label6" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 23 - $System_Drawing_Size.Width = 175 - $label6.Size = $System_Drawing_Size - $label6.Text = "VHD Name (Optional)" - - $groupBox3.Controls.Add($label6) - #endregion label6 - - #region btnUnattendBrowse - $btnUnattendBrowse.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 449 - $System_Drawing_Point.Y = 199 - $btnUnattendBrowse.Location = $System_Drawing_Point - $btnUnattendBrowse.Name = "btnUnattendBrowse" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 27 - $btnUnattendBrowse.Size = $System_Drawing_Size - $btnUnattendBrowse.TabIndex = 9 - $btnUnattendBrowse.Text = "..." - $btnUnattendBrowse.UseVisualStyleBackColor = $True - $btnUnattendBrowse.add_Click($btnUnattendBrowse_OnClick) - - $groupBox3.Controls.Add($btnUnattendBrowse) - #endregion btnUnattendBrowse - - #region btnWrkBrowse - $btnWrkBrowse.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 449 - $System_Drawing_Point.Y = 98 - $btnWrkBrowse.Location = $System_Drawing_Point - $btnWrkBrowse.Name = "btnWrkBrowse" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 27 - $btnWrkBrowse.Size = $System_Drawing_Size - $btnWrkBrowse.TabIndex = 9 - $btnWrkBrowse.Text = "..." - $btnWrkBrowse.UseVisualStyleBackColor = $True - $btnWrkBrowse.add_Click($btnWrkBrowse_OnClick) - - $groupBox3.Controls.Add($btnWrkBrowse) - #endregion btnWrkBrowse - - #region cmbVhdSizeUnit - $cmbVhdSizeUnit.DataBindings.DefaultDataSourceUpdateMode = 0 - $cmbVhdSizeUnit.FormattingEnabled = $True - $cmbVhdSizeUnit.Items.Add("MB") | Out-Null - $cmbVhdSizeUnit.Items.Add("GB") | Out-Null - $cmbVhdSizeUnit.Items.Add("TB") | Out-Null - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 409 - $System_Drawing_Point.Y = 42 - $cmbVhdSizeUnit.Location = $System_Drawing_Point - $cmbVhdSizeUnit.Name = "cmbVhdSizeUnit" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 67 - $cmbVhdSizeUnit.Size = $System_Drawing_Size - $cmbVhdSizeUnit.TabIndex = 5 - $cmbVhdSizeUnit.Text = $unit - - $groupBox3.Controls.Add($cmbVhdSizeUnit) - #endregion cmbVhdSizeUnit - - #region numVhdSize - $numVhdSize.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 340 - $System_Drawing_Point.Y = 42 - $numVhdSize.Location = $System_Drawing_Point - $numVhdSize.Name = "numVhdSize" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 63 - $numVhdSize.Size = $System_Drawing_Size - $numVhdSize.TabIndex = 4 - $numVhdSize.Value = $quantity - - $groupBox3.Controls.Add($numVhdSize) - #endregion numVhdSize - - #region cmbVhdFormat - $cmbVhdFormat.DataBindings.DefaultDataSourceUpdateMode = 0 - $cmbVhdFormat.FormattingEnabled = $True - $cmbVhdFormat.Items.Add("VHD") | Out-Null - $cmbVhdFormat.Items.Add("VHDX") | Out-Null - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 42 - $cmbVhdFormat.Location = $System_Drawing_Point - $cmbVhdFormat.Name = "cmbVhdFormat" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 136 - $cmbVhdFormat.Size = $System_Drawing_Size - $cmbVhdFormat.TabIndex = 0 - $cmbVhdFormat.Text = $VHDFormat - - $groupBox3.Controls.Add($cmbVhdFormat) - #endregion cmbVhdFormat - - #region label5 - $label5.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 23 - $System_Drawing_Point.Y = 76 - $label5.Location = $System_Drawing_Point - $label5.Name = "label5" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 23 - $System_Drawing_Size.Width = 264 - $label5.Size = $System_Drawing_Size - $label5.TabIndex = 8 - $label5.Text = "Working Directory" - - $groupBox3.Controls.Add($label5) - #endregion label5 - - #region txtWorkingDirectory - $txtWorkingDirectory.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 99 - $txtWorkingDirectory.Location = $System_Drawing_Point - $txtWorkingDirectory.Name = "txtWorkingDirectory" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 418 - $txtWorkingDirectory.Size = $System_Drawing_Size - $txtWorkingDirectory.TabIndex = 7 - $txtWorkingDirectory.Text = $WorkingDirectory - - $groupBox3.Controls.Add($txtWorkingDirectory) - #endregion txtWorkingDirectory - - #region label4 - $label4.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 340 - $System_Drawing_Point.Y = 21 - $label4.Location = $System_Drawing_Point - $label4.Name = "label4" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 27 - $System_Drawing_Size.Width = 86 - $label4.Size = $System_Drawing_Size - $label4.TabIndex = 6 - $label4.Text = "VHD Size" - - $groupBox3.Controls.Add($label4) - #endregion label4 - - #region label3 - $label3.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 176 - $System_Drawing_Point.Y = 21 - $label3.Location = $System_Drawing_Point - $label3.Name = "label3" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 27 - $System_Drawing_Size.Width = 92 - $label3.Size = $System_Drawing_Size - $label3.TabIndex = 3 - $label3.Text = "VHD Type" - - $groupBox3.Controls.Add($label3) - #endregion label3 - - #region label2 - $label2.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 21 - $label2.Location = $System_Drawing_Point - $label2.Name = "label2" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 30 - $System_Drawing_Size.Width = 118 - $label2.Size = $System_Drawing_Size - $label2.TabIndex = 1 - $label2.Text = "VHD Format" - - $groupBox3.Controls.Add($label2) - #endregion label2 - - #region groupBox2 - $groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 10 - $System_Drawing_Point.Y = 169 - $groupBox2.Location = $System_Drawing_Point - $groupBox2.Name = "groupBox2" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 68 - $System_Drawing_Size.Width = 490 - $groupBox2.Size = $System_Drawing_Size - $groupBox2.TabIndex = 6 - $groupBox2.TabStop = $False - $groupBox2.Text = "2. Choose a SKU from the list" - - $frmMain.Controls.Add($groupBox2) - #endregion groupBox2 - - #region cmbSkuList - $cmbSkuList.DataBindings.DefaultDataSourceUpdateMode = 0 - $cmbSkuList.FormattingEnabled = $True - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 24 - $cmbSkuList.Location = $System_Drawing_Point - $cmbSkuList.Name = "cmbSkuList" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 452 - $cmbSkuList.Size = $System_Drawing_Size - $cmbSkuList.TabIndex = 2 - - $groupBox2.Controls.Add($cmbSkuList) - #endregion cmbSkuList - - #region label1 - $label1.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 23 - $System_Drawing_Point.Y = 21 - $label1.Location = $System_Drawing_Point - $label1.Name = "label1" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 71 - $System_Drawing_Size.Width = 464 - $label1.Size = $System_Drawing_Size - $label1.TabIndex = 5 - $label1.Text = $uiHeader - - $frmMain.Controls.Add($label1) - #endregion label1 - - #region groupBox1 - $groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 10 - $System_Drawing_Point.Y = 95 - $groupBox1.Location = $System_Drawing_Point - $groupBox1.Name = "groupBox1" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 68 - $System_Drawing_Size.Width = 490 - $groupBox1.Size = $System_Drawing_Size - $groupBox1.TabIndex = 4 - $groupBox1.TabStop = $False - $groupBox1.Text = "1. Choose a source" - - $frmMain.Controls.Add($groupBox1) - #endregion groupBox1 - - #region txtSourcePath - $txtSourcePath.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 25 - $System_Drawing_Point.Y = 24 - $txtSourcePath.Location = $System_Drawing_Point - $txtSourcePath.Name = "txtSourcePath" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 418 - $txtSourcePath.Size = $System_Drawing_Size - $txtSourcePath.TabIndex = 0 - - $groupBox1.Controls.Add($txtSourcePath) - #endregion txtSourcePath - - #region btnBrowseWim - $btnBrowseWim.DataBindings.DefaultDataSourceUpdateMode = 0 - $System_Drawing_Point = New-Object System.Drawing.Point - $System_Drawing_Point.X = 449 - $System_Drawing_Point.Y = 24 - $btnBrowseWim.Location = $System_Drawing_Point - $btnBrowseWim.Name = "btnBrowseWim" - $System_Drawing_Size = New-Object System.Drawing.Size - $System_Drawing_Size.Height = 25 - $System_Drawing_Size.Width = 28 - $btnBrowseWim.Size = $System_Drawing_Size - $btnBrowseWim.TabIndex = 1 - $btnBrowseWim.Text = "..." - $btnBrowseWim.UseVisualStyleBackColor = $True - $btnBrowseWim.add_Click($btnBrowseWim_OnClick) - - $groupBox1.Controls.Add($btnBrowseWim) - #endregion btnBrowseWim - - $openFileDialog1.FileName = "openFileDialog1" - $openFileDialog1.ShowHelp = $True - - #endregion Form Code - - # Save the initial state of the form - $InitialFormWindowState = $frmMain.WindowState - - # Init the OnLoad event to correct the initial state of the form - $frmMain.add_Load($OnLoadForm_StateCorrection) - - # Return the constructed form. - $ret = $frmMain.ShowDialog() - - if (!($ret -ilike "OK")) - { - throw "Form session has been cancelled." - } - - if ([string]::IsNullOrEmpty($SourcePath)) - { - throw "No source path specified." - } - - # VHD Format - $VHDFormat = $cmbVhdFormat.SelectedItem - - # VHD Size - $SizeBytes = Invoke-Expression "$($numVhdSize.Value)$($cmbVhdSizeUnit.SelectedItem)" - - # Working Directory - $WorkingDirectory = $txtWorkingDirectory.Text - - # VHDPath - if (![string]::IsNullOrEmpty($txtVhdName.Text)) - { - $VHDPath = "$($WorkingDirectory)\$($txtVhdName.Text)" - } - - # Edition - if (![string]::IsNullOrEmpty($cmbSkuList.SelectedItem)) - { - $Edition = $cmbSkuList.SelectedItem - } - - # Because we used ShowDialog, we need to manually dispose of the form. - # This probably won't make much of a difference, but let's free up all of the resources we can - # before we start the conversion process. - - $frmMain.Dispose() - } - - if ($VHDFormat -ilike "AUTO") - { - if ($DiskLayout -eq "BIOS") - { - $VHDFormat = "VHD" - } - else - { - $VHDFormat = "VHDX" - } - } - - # - # Choose smallest supported block size for dynamic VHD(X) - # - $BlockSizeBytes = 1MB - - # There's a difference between the maximum sizes for VHDs and VHDXs. Make sure we follow it. - if ("VHD" -ilike $VHDFormat) - { - if ($SizeBytes -gt $vhdMaxSize) - { - Write-W2VWarn "For the VHD file format, the maximum file size is ~2040GB. We're automatically setting the size to 2040GB for you." - $SizeBytes = 2040GB - } - - $BlockSizeBytes = 512KB - } - - # Check if -VHDPath and -WorkingDirectory were both specified. - if ((![String]::IsNullOrEmpty($VHDPath)) -and (![String]::IsNullOrEmpty($WorkingDirectory))) - { - if ($WorkingDirectory -ne $pwd) - { - # If the WorkingDirectory is anything besides $pwd, tell people that the WorkingDirectory is being ignored. - Write-W2VWarn "Specifying -VHDPath and -WorkingDirectory at the same time is contradictory." - Write-W2VWarn "Ignoring the WorkingDirectory specification." - $WorkingDirectory = Split-Path $VHDPath -Parent - } - } - - if ($VHDPath) - { - # Check to see if there's a conflict between the specified file extension and the VHDFormat being used. - $ext = ([IO.FileInfo]$VHDPath).Extension - - if (!($ext -ilike ".$($VHDFormat)")) - { - throw "There is a mismatch between the VHDPath file extension ($($ext.ToUpper())), and the VHDFormat (.$($VHDFormat)). Please ensure that these match and try again." - } - } - - # Create a temporary name for the VHD(x). We'll name it properly at the end of the script. - if ([String]::IsNullOrEmpty($VHDPath)) - { - $VHDPath = Join-Path $WorkingDirectory "$($sessionKey).$($VHDFormat.ToLower())" - } - else - { - # Since we can't do Resolve-Path against a file that doesn't exist, we need to get creative in determining - # the full path that the user specified (or meant to specify if they gave us a relative path). - # Check to see if the path has a root specified. If it doesn't, use the working directory. - if (![IO.Path]::IsPathRooted($VHDPath)) - { - $VHDPath = Join-Path $WorkingDirectory $VHDPath - } - - $vhdFinalName = Split-Path $VHDPath -Leaf - $VHDPath = Join-Path (Split-Path $VHDPath -Parent) "$($sessionKey).$($VHDFormat.ToLower())" - } - - Write-W2VTrace "Temporary $VHDFormat path is : $VHDPath" - - # If we're using an ISO, mount it and get the path to the WIM file. - if (([IO.FileInfo]$SourcePath).Extension -ilike ".ISO") - { - # If the ISO isn't local, copy it down so we don't have to worry about resource contention - # or about network latency. - if (Test-IsNetworkLocation $SourcePath) - { - Write-W2VError "ISO Path cannot be network location" - #Write-W2VInfo "Copying ISO $(Split-Path $SourcePath -Leaf) to temp folder..." - #robocopy $(Split-Path $SourcePath -Parent) $TempDirectory $(Split-Path $SourcePath -Leaf) | Out-Null - #$SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)" - #$tempSource = $SourcePath - } - - $isoPath = (Resolve-Path $SourcePath).Path - - Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..." - <# - $openIso = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru - # Refresh the DiskImage object so we can get the real information about it. I assume this is a bug. - $openIso = Get-DiskImage -ImagePath $isoPath - $driveLetter = ($openIso | Get-Volume).DriveLetter - #> - $SourcePath = "$($DriveLetter):\sources\install.wim" - - # Check to see if there's a WIM file we can muck about with. - Write-W2VInfo "Looking for $($SourcePath)..." - if (!(Test-Path $SourcePath)) - { - throw "The specified ISO does not appear to be valid Windows installation media." - } - } - - # Check to see if the WIM is local, or on a network location. If the latter, copy it locally. - if (Test-IsNetworkLocation $SourcePath) - { - Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..." - robocopy $(Split-Path $SourcePath -Parent) $TempDirectory $(Split-Path $SourcePath -Leaf) | Out-Null - $SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)" - - $tempSource = $SourcePath - } - - $SourcePath = (Resolve-Path $SourcePath).Path - - #################################################################################################### - # QUERY WIM INFORMATION AND EXTRACT THE INDEX OF TARGETED IMAGE - #################################################################################################### - - Write-W2VInfo "Looking for the requested Windows image in the WIM file" - $WindowsImage = Get-WindowsImage -ImagePath "$($driveLetter):\sources\install.wim" - - if (-not $WindowsImage -or ($WindowsImage -is [System.Array])) - { - # - # WIM may have multiple images. Filter on Edition (can be index or name) and try to find a unique image - # - $EditionIndex = 0; - if ([Int32]::TryParse($Edition, [ref]$EditionIndex)) - { - $WindowsImage = Get-WindowsImage -ImagePath $SourcePath -Index $EditionIndex - } - else - { - $WindowsImage = Get-WindowsImage -ImagePath $SourcePath | Where-Object {$_.ImageName -ilike "*$($Edition)"} - } - - if (-not $WindowsImage) - { - throw "Requested windows Image was not found on the WIM file!" - } - if ($WindowsImage -is [System.Array]) - { - Write-W2VInfo "WIM file has the following $($WindowsImage.Count) images that match filter *$($Edition)" - Get-WindowsImage -ImagePath $SourcePath - - Write-W2VError "You must specify an Edition or SKU index, since the WIM has more than one image." - throw "There are more than one images that match ImageName filter *$($Edition)" - } - } - - $ImageIndex = $WindowsImage[0].ImageIndex - - # We're good. Open the WIM container. - # NOTE: this is only required because we want to get the XML-based meta-data at the end. Is there a better way? - # If we can get this information from DISM cmdlets, we can remove the openWim constructs - $openWim = New-Object WIM2VHD.WimFile $SourcePath - - $openImage = $openWim[[Int32]$ImageIndex] - - if ($null -eq $openImage) - { - Write-W2VError "The specified edition does not appear to exist in the specified WIM." - Write-W2VError "Valid edition names are:" - $openWim.Images | %{ Write-W2VError " $($_.ImageFlags)" } - throw - } - - Write-W2VInfo "Image $($openImage.ImageIndex) selected ($($openImage.ImageFlags))..." - - # Check to make sure that the image we're applying is Windows 7 or greater. - if ($openImage.ImageVersion -lt $lowestSupportedVersion) - { - if ($openImage.ImageVersion -eq "0.0.0.0") - { - Write-W2VWarn "The specified WIM does not encode the Windows version." - } - else - { - throw "Convert-WindowsImage only supports Windows 7 and Windows 8 WIM files. The specified image (version $($openImage.ImageVersion)) does not appear to contain one of those operating systems." - } - } - - if ($hyperVEnabled) - { - Write-W2VInfo "Creating sparse disk..." - $newVhd = New-VHD -Path $VHDPath -SizeBytes $SizeBytes -BlockSizeBytes $BlockSizeBytes -Dynamic - - Write-W2VInfo "Mounting $VHDFormat..." - $disk = $newVhd | Mount-VHD -PassThru | Get-Disk - } - else - { - <# - Create the VHD using the VirtDisk Win32 API. - So, why not use the New-VHD cmdlet here? - - New-VHD depends on the Hyper-V Cmdlets, which aren't installed by default. - Installing those cmdlets isn't a big deal, but they depend on the Hyper-V WMI - APIs, which in turn depend on Hyper-V. In order to prevent Convert-WindowsImage - from being dependent on Hyper-V (and thus, x64 systems only), we're using the - VirtDisk APIs directly. - #> - - Write-W2VInfo "Creating sparse disk..." - [WIM2VHD.VirtualHardDisk]::CreateSparseDisk( - $VHDFormat, - $VHDPath, - $SizeBytes, - $true - ) - - # Attach the VHD.\ - Write-W2VInfo "Attaching $VHDFormat..." - $disk = Mount-DiskImage -ImagePath $VHDPath -PassThru | Get-DiskImage | Get-Disk - } - - switch ($DiskLayout) - { - "BIOS" - { - Write-W2VInfo "Initializing disk..." - Initialize-Disk -Number $disk.Number -PartitionStyle MBR - - # - # Create the Windows/system partition - # - Write-W2VInfo "Creating single partition..." - $systemPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -MbrType IFS -IsActive - $windowsPartition = $systemPartition - - Write-W2VInfo "Formatting windows volume..." - $systemVolume = Format-Volume -Partition $systemPartition -FileSystem NTFS -Force -Confirm:$false - $windowsVolume = $systemVolume - } - - "UEFI" - { - Write-W2VInfo "Initializing disk..." - Initialize-Disk -Number $disk.Number -PartitionStyle GPT - - if ((Get-WindowsBuildNumber) -ge 10240) - { - # - # Create the system partition. Create a data partition so we can format it, then change to ESP - # - Write-W2VInfo "Creating EFI system partition..." - $systemPartition = New-Partition -DiskNumber $disk.Number -Size 200MB -GptType '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}' - - Write-W2VInfo "Formatting system volume..." - $systemVolume = Format-Volume -Partition $systemPartition -FileSystem FAT32 -Force -Confirm:$false - - Write-W2VInfo "Setting system partition as ESP..." - $systemPartition | Set-Partition -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' - $systemPartition | Add-PartitionAccessPath -AssignDriveLetter - } - else - { - # - # Create the system partition - # - Write-W2VInfo "Creating EFI system partition (ESP)..." - $systemPartition = New-Partition -DiskNumber $disk.Number -Size 200MB -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -AssignDriveLetter - - Write-W2VInfo "Formatting ESP..." - $formatArgs = @( - "$($systemPartition.DriveLetter):", # Partition drive letter - "/FS:FAT32", # File system - "/Q", # Quick format - "/Y" # Suppress prompt - ) - - Run-Executable -Executable format -Arguments $formatArgs - } - - # - # Create the reserved partition - # - Write-W2VInfo "Creating MSR partition..." - $reservedPartition = New-Partition -DiskNumber $disk.Number -Size 128MB -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}' - - # - # Create the Windows partition - # - Write-W2VInfo "Creating windows partition..." - $windowsPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -GptType '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}' - - Write-W2VInfo "Formatting windows volume..." - $windowsVolume = Format-Volume -Partition $windowsPartition -FileSystem NTFS -Force -Confirm:$false - } - - "WindowsToGo" - { - Write-W2VInfo "Initializing disk..." - Initialize-Disk -Number $disk.Number -PartitionStyle MBR - - # - # Create the system partition - # - Write-W2VInfo "Creating system partition..." - $systemPartition = New-Partition -DiskNumber $disk.Number -Size 350MB -MbrType FAT32 -IsActive - - Write-W2VInfo "Formatting system volume..." - $systemVolume = Format-Volume -Partition $systemPartition -FileSystem FAT32 -Force -Confirm:$false - - # - # Create the Windows partition - # - Write-W2VInfo "Creating windows partition..." - $windowsPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -MbrType IFS - - Write-W2VInfo "Formatting windows volume..." - $windowsVolume = Format-Volume -Partition $windowsPartition -FileSystem NTFS -Force -Confirm:$false - } - } - - # - # Assign drive letter to Windows partition. This is required for bcdboot - # - - $attempts = 1 - $assigned = $false - - do - { - $windowsPartition | Add-PartitionAccessPath -AssignDriveLetter - $windowsPartition = $windowsPartition | Get-Partition - if($windowsPartition.DriveLetter -ne 0) - { - $assigned = $true - } - else - { - #sleep for up to 10 seconds and retry - Get-Random -Minimum 1 -Maximum 10 | Start-Sleep - - $attempts++ - } - } - while ($attempts -le 100 -and -not($assigned)) - - if (-not($assigned)) - { - throw "Unable to get Partition after retry" - } - - $windowsDrive = $(Get-Partition -Volume $windowsVolume).AccessPaths[0].substring(0,2) - Write-W2VInfo "Windows path ($windowsDrive) has been assigned." - Write-W2VInfo "Windows path ($windowsDrive) took $attempts attempts to be assigned." - - # - # Refresh access paths (we have now formatted the volume) - # - $systemPartition = $systemPartition | Get-Partition - $systemDrive = $systemPartition.AccessPaths[0].trimend("\").replace("\?", "??") - Write-W2VInfo "System volume location: $systemDrive" - - #################################################################################################### - # APPLY IMAGE FROM WIM TO THE NEW VHD - #################################################################################################### - - Write-W2VInfo "Applying image to $VHDFormat. This could take a while..." - if ((Get-Command Expand-WindowsImage -ErrorAction SilentlyContinue) -and ((-not $ApplyEA) -and ([string]::IsNullOrEmpty($DismPath)))) - { - Expand-WindowsImage -ApplyPath $windowsDrive -ImagePath $SourcePath -Index $ImageIndex -LogPath "$($logFolder)\DismLogs.log" | Out-Null - } - else - { - if (![string]::IsNullOrEmpty($DismPath)) - { - $dismPath = $DismPath - } - else - { - $dismPath = $(Join-Path (get-item env:\windir).value "system32\dism.exe") - } - - $applyImage = "/Apply-Image" - if ($ApplyEA) - { - $applyImage = $applyImage + " /EA" - } - - $dismArgs = @("$applyImage /ImageFile:`"$SourcePath`" /Index:$ImageIndex /ApplyDir:$windowsDrive /LogPath:`"$($logFolder)\DismLogs.log`"") - Write-W2VInfo "Applying image: $dismPath $dismArgs" - $process = Start-Process -Passthru -Wait -NoNewWindow -FilePath $dismPath ` - -ArgumentList $dismArgs ` - - if ($process.ExitCode -ne 0) - { - throw "Image Apply failed! See DismImageApply logs for details" - } - } - Write-W2VInfo "Image was applied successfully. " - - # - # Here we copy in the unattend file (if specified by the command line) - # - if (![string]::IsNullOrEmpty($UnattendPath)) - { - Write-W2VInfo "Applying unattend file ($(Split-Path $UnattendPath -Leaf))..." - Copy-Item -Path $UnattendPath -Destination (Join-Path $windowsDrive "unattend.xml") -Force - } - - if (![string]::IsNullOrEmpty($MergeFolderPath)) - { - Write-W2VInfo "Applying merge folder ($MergeFolderPath)..." - Copy-Item -Recurse -Path (Join-Path $MergeFolderPath "*") -Destination $windowsDrive -Force #added to handle merge folders - } - - if (($openImage.ImageArchitecture -ne "ARM") -and # No virtualization platform for ARM images - ($openImage.ImageArchitecture -ne "ARM64") -and # No virtualization platform for ARM64 images - ($BCDinVHD -ne "NativeBoot")) # User asked for a non-bootable image - { - if (Test-Path "$($systemDrive)\boot\bcd") - { - Write-W2VInfo "Image already has BIOS BCD store..." - } - elseif (Test-Path "$($systemDrive)\efi\microsoft\boot\bcd") - { - Write-W2VInfo "Image already has EFI BCD store..." - } - else - { - Write-W2VInfo "Making image bootable..." - $bcdBootArgs = @( - "$($windowsDrive)\Windows", # Path to the \Windows on the VHD - "/s $systemDrive", # Specifies the volume letter of the drive to create the \BOOT folder on. - "/v" # Enabled verbose logging. - ) - - switch ($DiskLayout) - { - "BIOS" - { - $bcdBootArgs += "/f BIOS" # Specifies the firmware type of the target system partition - } - - "UEFI" - { - $bcdBootArgs += "/f UEFI" # Specifies the firmware type of the target system partition - } - - "WindowsToGo" - { - # Create entries for both UEFI and BIOS if possible - if (Test-Path "$($windowsDrive)\Windows\boot\EFI\bootmgfw.efi") - { - $bcdBootArgs += "/f ALL" - } - } - } - - Run-Executable -Executable $BCDBoot -Arguments $bcdBootArgs - - # The following is added to mitigate the VMM diff disk handling - # We're going to change from MBRBootOption to LocateBootOption. - - if ($DiskLayout -eq "BIOS") - { - Write-W2VInfo "Fixing the Device ID in the BCD store on $($VHDFormat)..." - Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( - "/store $($systemDrive)\boot\bcd", - "/set `{bootmgr`} device locate" - ) - Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( - "/store $($systemDrive)\boot\bcd", - "/set `{default`} device locate" - ) - Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( - "/store $($systemDrive)\boot\bcd", - "/set `{default`} osdevice locate" - ) - } - } - - Write-W2VInfo "Drive is bootable. Cleaning up..." - - # Are we turning the debugger on? - if ($EnableDebugger -inotlike "None") - { - $bcdEditArgs = $null; - - # Configure the specified debugging transport and other settings. - switch ($EnableDebugger) - { - "Serial" - { - $bcdEditArgs = @( - "/dbgsettings SERIAL", - "DEBUGPORT:$($ComPort.Value)", - "BAUDRATE:$($BaudRate.Value)" - ) - } - - "1394" - { - $bcdEditArgs = @( - "/dbgsettings 1394", - "CHANNEL:$($Channel.Value)" - ) - } - - "USB" - { - $bcdEditArgs = @( - "/dbgsettings USB", - "TARGETNAME:$($Target.Value)" - ) - } - - "Local" - { - $bcdEditArgs = @( - "/dbgsettings LOCAL" - ) - } - - "Network" - { - $bcdEditArgs = @( - "/dbgsettings NET", - "HOSTIP:$($IP.Value)", - "PORT:$($Port.Value)", - "KEY:$($Key.Value)" - ) - } - } - - $bcdStores = @( - "$($systemDrive)\boot\bcd", - "$($systemDrive)\efi\microsoft\boot\bcd" - ) - - foreach ($bcdStore in $bcdStores) - { - if (Test-Path $bcdStore) - { - Write-W2VInfo "Turning kernel debugging on in the $($VHDFormat) for $($bcdStore)..." - Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( - "/store $($bcdStore)", - "/set `{default`} debug on" - ) - - $bcdEditArguments = @("/store $($bcdStore)") + $bcdEditArgs - - Run-Executable -Executable "BCDEDIT.EXE" -Arguments $bcdEditArguments - } - } - } - } - else - { - # Don't bother to check on debugging. We can't boot WoA VHDs in VMs, and - # if we're native booting, the changes need to be made to the BCD store on the - # physical computer's boot volume. - - Write-W2VInfo "Image applied. It is not bootable." - } - - if ($RemoteDesktopEnable -or (-not $ExpandOnNativeBoot)) - { - $hive = Mount-RegistryHive -Hive (Join-Path $windowsDrive "Windows\System32\Config\System") - - if ($RemoteDesktopEnable) - { - Write-W2VInfo -text "Enabling Remote Desktop" - Set-ItemProperty -Path "HKLM:\$($hive)\ControlSet001\Control\Terminal Server" -Name "fDenyTSConnections" -Value 0 - } - - if (-not $ExpandOnNativeBoot) - { - Write-W2VInfo -text "Disabling automatic $VHDFormat expansion for Native Boot" - Set-ItemProperty -Path "HKLM:\$($hive)\ControlSet001\Services\FsDepends\Parameters" -Name "VirtualDiskExpandOnMount" -Value 4 - } - - Dismount-RegistryHive -HiveMountPoint $hive - } - - if ($Driver) - { - Write-W2VInfo -text "Adding Windows Drivers to the Image" - $Driver | ForEach-Object -Process { - Write-W2VInfo -text "Driver path: $PSItem" - Add-WindowsDriver -Path $windowsDrive -Recurse -Driver $PSItem -Verbose | Out-Null - } - } - - If ($Feature) - { - Write-W2VInfo -text "Installing Windows Feature(s) $Feature to the Image" - $FeatureSourcePath = Join-Path -Path "$($driveLetter):" -ChildPath "sources\sxs" - Write-W2VInfo -text "From $FeatureSourcePath" - Enable-WindowsOptionalFeature -FeatureName $Feature -Source $FeatureSourcePath -Path $windowsDrive -All | Out-Null - } - - if ($Package) - { - Write-W2VInfo -text "Adding Windows Packages to the Image" - - $Package | ForEach-Object -Process { - Write-W2VInfo -text "Package path: $PSItem" - Add-WindowsPackage -Path $windowsDrive -PackagePath $PSItem | Out-Null - } - } - - # - # Remove system partition access path, if necessary - # - - if (($GPUName)) { - Add-VMGpuPartitionAdapterFiles -GPUName $GPUName -DriveLetter $windowsDrive - } - - Write-W2VInfo "Setting up Parsec to install at boot" - Setup-ParsecInstall -DriveLetter $WindowsDrive -Team_ID $team_id -Key $key - - if ($DiskLayout -eq "UEFI") - { - $systemPartition | Remove-PartitionAccessPath -AccessPath $systemPartition.AccessPaths[0] - } - - if ([String]::IsNullOrEmpty($vhdFinalName)) - { - # We need to generate a file name. - Write-W2VInfo "Generating name for $($VHDFormat)..." - $hive = Mount-RegistryHive -Hive (Join-Path $windowsDrive "Windows\System32\Config\Software") - - $buildLabEx = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").BuildLabEx - $installType = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").InstallationType - $editionId = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").EditionID - $skuFamily = $null - - Dismount-RegistryHive -HiveMountPoint $hive - - # Is this ServerCore? - # Since we're only doing this string comparison against the InstallType key, we won't get - # false positives with the Core SKU. - if ($installType.ToUpper().Contains("CORE")) - { - $editionId += "Core" - } - - # What type of SKU are we? - if ($installType.ToUpper().Contains("SERVER")) - { - $skuFamily = "Server" - } - elseif ($installType.ToUpper().Contains("CLIENT")) - { - $skuFamily = "Client" - } - else - { - $skuFamily = "Unknown" - } - - # - # ISSUE - do we want VL here? - # - $vhdFinalName = "$($buildLabEx)_$($skuFamily)_$($editionId)_$($openImage.ImageDefaultLanguage).$($VHDFormat.ToLower())" - Write-W2VTrace "$VHDFormat final name is : $vhdFinalName" - } - - if ($hyperVEnabled) - { - Write-W2VInfo "Dismounting $VHDFormat..." - Dismount-VHD -Path $VHDPath - } - else - { - Write-W2VInfo "Closing $VHDFormat..." - Dismount-DiskImage -ImagePath $VHDPath - } - - $vhdFinalPath = Join-Path (Split-Path $VHDPath -Parent) $vhdFinalName - Write-W2VTrace "$VHDFormat final path is : $vhdFinalPath" - - if (Test-Path $vhdFinalPath) - { - Write-W2VInfo "Deleting pre-existing $VHDFormat : $(Split-Path $vhdFinalPath -Leaf)..." - Remove-Item -Path $vhdFinalPath -Force - } - - Write-W2VTrace -Text "Renaming $VHDFormat at $VHDPath to $vhdFinalName" - Rename-Item -Path (Resolve-Path $VHDPath).Path -NewName $vhdFinalName -Force - $vhd += Get-DiskImage -ImagePath $vhdFinalPath - - $vhdFinalName = $null - } - catch - { - Write-W2VError $_ - Write-W2VInfo "Log folder is $logFolder" - } - finally - { - # If we still have a WIM image open, close it. - if ($openWim -ne $null) - { - Write-W2VInfo "Closing Windows image..." - $openWim.Close() - } - - # If we still have a registry hive mounted, dismount it. - if ($mountedHive -ne $null) - { - Write-W2VInfo "Closing registry hive..." - Dismount-RegistryHive -HiveMountPoint $mountedHive - } - - # If VHD is mounted, unmount it - if (Test-Path $VHDPath) - { - if ($hyperVEnabled) - { - if ((Get-VHD -Path $VHDPath).Attached) - { - Dismount-VHD -Path $VHDPath - } - } - else - { - Dismount-DiskImage -ImagePath $VHDPath - } - } - - # If we still have an ISO open, close it. - if ($openIso -ne $null) - { - Write-W2VInfo "Closing ISO..." - Dismount-DiskImage $ISOPath - } - - if (-not $CacheSource) - { - if ($tempSource -and (Test-Path $tempSource)) - { - Remove-Item -Path $tempSource -Force - } - } - - # Close out the transcript and tell the user we're done. - Dismount-ISO -SourcePath $ISOPath - Write-W2VInfo "Done." - if ($transcripting) - { - $null = Stop-Transcript - } - } - } - - End - { - if ($Passthru) - { - return $vhd - } - } - #endregion Code - -} - -function Add-WindowsImageTypes { - $code = @" -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Xml.Linq; -using System.Xml.XPath; -using Microsoft.Win32.SafeHandles; - -namespace WIM2VHD -{ - -/// -/// P/Invoke methods and associated enums, flags, and structs. -/// -public class -NativeMethods -{ - - #region Delegates and Callbacks - #region WIMGAPI - - /// - ///User-defined function used with the RegisterMessageCallback or UnregisterMessageCallback function. - /// - ///Specifies the message being sent. - ///Specifies additional message information. The contents of this parameter depend on the value of the - ///MessageId parameter. - ///Specifies additional message information. The contents of this parameter depend on the value of the - ///MessageId parameter. - ///Specifies the user-defined value passed to RegisterCallback. - /// - ///To indicate success and to enable other subscribers to process the message return WIM_MSG_SUCCESS. - ///To prevent other subscribers from receiving the message, return WIM_MSG_DONE. - ///To cancel an image apply or capture, return WIM_MSG_ABORT_IMAGE when handling the WIM_MSG_PROCESS message. - /// - public delegate uint - WimMessageCallback( - uint MessageId, - IntPtr wParam, - IntPtr lParam, - IntPtr UserData - ); - - public static void - RegisterMessageCallback( - WimFileHandle hWim, - WimMessageCallback callback) - { - - uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero); - int rc = Marshal.GetLastWin32Error(); - if (0 != rc) - { - // Throw an exception if something bad happened on the Win32 end. - throw - new InvalidOperationException( - string.Format( - CultureInfo.CurrentCulture, - "Unable to register message callback." - )); - } - } - - public static void - UnregisterMessageCallback( - WimFileHandle hWim, - WimMessageCallback registeredCallback) - { - - bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback); - int rc = Marshal.GetLastWin32Error(); - if (!status) - { - throw - new InvalidOperationException( - string.Format( - CultureInfo.CurrentCulture, - "Unable to unregister message callback." - )); - } - } - - #endregion WIMGAPI - #endregion Delegates and Callbacks - - #region Constants - - #region VDiskInterop - - /// - /// The default depth in a VHD parent chain that this library will search through. - /// If you want to go more than one disk deep into the parent chain, provide a different value. - /// - public const uint OPEN_VIRTUAL_DISK_RW_DEFAULT_DEPTH = 0x00000001; - - public const uint DEFAULT_BLOCK_SIZE = 0x00080000; - public const uint DISK_SECTOR_SIZE = 0x00000200; - - internal const uint ERROR_VIRTDISK_NOT_VIRTUAL_DISK = 0xC03A0015; - internal const uint ERROR_NOT_FOUND = 0x00000490; - internal const uint ERROR_IO_PENDING = 0x000003E5; - internal const uint ERROR_INSUFFICIENT_BUFFER = 0x0000007A; - internal const uint ERROR_ERROR_DEV_NOT_EXIST = 0x00000037; - internal const uint ERROR_BAD_COMMAND = 0x00000016; - internal const uint ERROR_SUCCESS = 0x00000000; - - public const uint GENERIC_READ = 0x80000000; - public const uint GENERIC_WRITE = 0x40000000; - public const short FILE_ATTRIBUTE_NORMAL = 0x00000080; - public const uint CREATE_NEW = 0x00000001; - public const uint CREATE_ALWAYS = 0x00000002; - public const uint OPEN_EXISTING = 0x00000003; - public const short INVALID_HANDLE_VALUE = -1; - - internal static Guid VirtualStorageTypeVendorUnknown = new Guid("00000000-0000-0000-0000-000000000000"); - internal static Guid VirtualStorageTypeVendorMicrosoft = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B"); - - #endregion VDiskInterop - - #region WIMGAPI - - public const uint WIM_FLAG_VERIFY = 0x00000002; - public const uint WIM_FLAG_INDEX = 0x00000004; - - public const uint WM_APP = 0x00008000; - - #endregion WIMGAPI - - #endregion Constants - - #region Enums and Flags - - #region VDiskInterop - - /// - /// Indicates the version of the virtual disk to create. - /// - public enum CreateVirtualDiskVersion : int - { - VersionUnspecified = 0x00000000, - Version1 = 0x00000001, - Version2 = 0x00000002 - } - - public enum OpenVirtualDiskVersion : int - { - VersionUnspecified = 0x00000000, - Version1 = 0x00000001, - Version2 = 0x00000002 - } - - /// - /// Contains the version of the virtual hard disk (VHD) ATTACH_VIRTUAL_DISK_PARAMETERS structure to use in calls to VHD functions. - /// - public enum AttachVirtualDiskVersion : int - { - VersionUnspecified = 0x00000000, - Version1 = 0x00000001, - Version2 = 0x00000002 - } - - public enum CompactVirtualDiskVersion : int - { - VersionUnspecified = 0x00000000, - Version1 = 0x00000001 - } - - /// - /// Contains the type and provider (vendor) of the virtual storage device. - /// - public enum VirtualStorageDeviceType : int - { - /// - /// The storage type is unknown or not valid. - /// - Unknown = 0x00000000, - /// - /// For internal use only. This type is not supported. - /// - ISO = 0x00000001, - /// - /// Virtual Hard Disk device type. - /// - VHD = 0x00000002, - /// - /// Virtual Hard Disk v2 device type. - /// - VHDX = 0x00000003 - } - - /// - /// Contains virtual hard disk (VHD) open request flags. - /// - [Flags] - public enum OpenVirtualDiskFlags - { - /// - /// No flags. Use system defaults. - /// - None = 0x00000000, - /// - /// Open the VHD file (backing store) without opening any differencing-chain parents. Used to correct broken parent links. - /// - NoParents = 0x00000001, - /// - /// Reserved. - /// - BlankFile = 0x00000002, - /// - /// Reserved. - /// - BootDrive = 0x00000004, - } - - /// - /// Contains the bit mask for specifying access rights to a virtual hard disk (VHD). - /// - [Flags] - public enum VirtualDiskAccessMask - { - /// - /// Only Version2 of OpenVirtualDisk API accepts this parameter - /// - None = 0x00000000, - /// - /// Open the virtual disk for read-only attach access. The caller must have READ access to the virtual disk image file. - /// - /// - /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either - /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail. - /// - AttachReadOnly = 0x00010000, - /// - /// Open the virtual disk for read-write attaching access. The caller must have (READ | WRITE) access to the virtual disk image file. - /// - /// - /// If used in a request to open a virtual disk that is already open, the other handles must be limited to either - /// VIRTUAL_DISK_ACCESS_DETACH or VIRTUAL_DISK_ACCESS_GET_INFO access, otherwise the open request with this flag will fail. - /// If the virtual disk is part of a differencing chain, the disk for this request cannot be less than the readWriteDepth specified - /// during the prior open request for that differencing chain. - /// - AttachReadWrite = 0x00020000, - /// - /// Open the virtual disk to allow detaching of an attached virtual disk. The caller must have - /// (FILE_READ_ATTRIBUTES | FILE_READ_DATA) access to the virtual disk image file. - /// - Detach = 0x00040000, - /// - /// Information retrieval access to the virtual disk. The caller must have READ access to the virtual disk image file. - /// - GetInfo = 0x00080000, - /// - /// Virtual disk creation access. - /// - Create = 0x00100000, - /// - /// Open the virtual disk to perform offline meta-operations. The caller must have (READ | WRITE) access to the virtual - /// disk image file, up to readWriteDepth if working with a differencing chain. - /// - /// - /// If the virtual disk is part of a differencing chain, the backing store (host volume) is opened in RW exclusive mode up to readWriteDepth. - /// - MetaOperations = 0x00200000, - /// - /// Reserved. - /// - Read = 0x000D0000, - /// - /// Allows unrestricted access to the virtual disk. The caller must have unrestricted access rights to the virtual disk image file. - /// - All = 0x003F0000, - /// - /// Reserved. - /// - Writable = 0x00320000 - } - - /// - /// Contains virtual hard disk (VHD) creation flags. - /// - [Flags] - public enum CreateVirtualDiskFlags - { - /// - /// Contains virtual hard disk (VHD) creation flags. - /// - None = 0x00000000, - /// - /// Pre-allocate all physical space necessary for the size of the virtual disk. - /// - /// - /// The CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION flag is used for the creation of a fixed VHD. - /// - FullPhysicalAllocation = 0x00000001 - } - - /// - /// Contains virtual disk attach request flags. - /// - [Flags] - public enum AttachVirtualDiskFlags - { - /// - /// No flags. Use system defaults. - /// - None = 0x00000000, - /// - /// Attach the virtual disk as read-only. - /// - ReadOnly = 0x00000001, - /// - /// No drive letters are assigned to the disk's volumes. - /// - /// Oddly enough, this doesn't apply to NTFS mount points. - NoDriveLetter = 0x00000002, - /// - /// Will decouple the virtual disk lifetime from that of the VirtualDiskHandle. - /// The virtual disk will be attached until the Detach() function is called, even if all open handles to the virtual disk are closed. - /// - PermanentLifetime = 0x00000004, - /// - /// Reserved. - /// - NoLocalHost = 0x00000008 - } - - [Flags] - public enum DetachVirtualDiskFlag - { - None = 0x00000000 - } - - [Flags] - public enum CompactVirtualDiskFlags - { - None = 0x00000000, - NoZeroScan = 0x00000001, - NoBlockMoves = 0x00000002 - } - - #endregion VDiskInterop - - #region WIMGAPI - - [FlagsAttribute] - internal enum - WimCreateFileDesiredAccess : uint - { - WimQuery = 0x00000000, - WimGenericRead = 0x80000000 - } - - public enum WimMessage : uint - { - WIM_MSG = WM_APP + 0x1476, - WIM_MSG_TEXT, - /// - ///Indicates an update in the progress of an image application. - /// - WIM_MSG_PROGRESS, - /// - ///Enables the caller to prevent a file or a directory from being captured or applied. - /// - WIM_MSG_PROCESS, - /// - ///Indicates that volume information is being gathered during an image capture. - /// - WIM_MSG_SCANNING, - /// - ///Indicates the number of files that will be captured or applied. - /// - WIM_MSG_SETRANGE, - /// - ///Indicates the number of files that have been captured or applied. - /// - WIM_MSG_SETPOS, - /// - ///Indicates that a file has been either captured or applied. - /// - WIM_MSG_STEPIT, - /// - ///Enables the caller to prevent a file resource from being compressed during a capture. - /// - WIM_MSG_COMPRESS, - /// - ///Alerts the caller that an error has occurred while capturing or applying an image. - /// - WIM_MSG_ERROR, - /// - ///Enables the caller to align a file resource on a particular alignment boundary. - /// - WIM_MSG_ALIGNMENT, - WIM_MSG_RETRY, - /// - ///Enables the caller to align a file resource on a particular alignment boundary. - /// - WIM_MSG_SPLIT, - WIM_MSG_SUCCESS = 0x00000000, - WIM_MSG_ABORT_IMAGE = 0xFFFFFFFF - } - - internal enum - WimCreationDisposition : uint - { - WimOpenExisting = 0x00000003, - } - - internal enum - WimActionFlags : uint - { - WimIgnored = 0x00000000 - } - - internal enum - WimCompressionType : uint - { - WimIgnored = 0x00000000 - } - - internal enum - WimCreationResult : uint - { - WimCreatedNew = 0x00000000, - WimOpenedExisting = 0x00000001 - } - - #endregion WIMGAPI - - #endregion Enums and Flags - - #region Structs - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct CreateVirtualDiskParameters - { - /// - /// 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. - /// - public CreateVirtualDiskVersion Version; - - /// - /// Unique identifier to assign to the virtual disk object. If this member is set to zero, a unique identifier is created by the system. - /// - public Guid UniqueId; - - /// - /// The maximum virtual size of the virtual disk object. Must be a multiple of 512. - /// If a ParentPath is specified, this value must be zero. - /// If a SourcePath is specified, this value can be zero to specify the size of the source VHD to be used, otherwise the size specified must be greater than or equal to the size of the source disk. - /// - public ulong MaximumSize; - - /// - /// Internal size of the virtual disk object blocks. - /// The following are predefined block sizes and their behaviors. For a fixed VHD type, this parameter must be zero. - /// - public uint BlockSizeInBytes; - - /// - /// Internal size of the virtual disk object sectors. Must be set to 512. - /// - public uint SectorSizeInBytes; - - /// - /// Optional path to a parent virtual disk object. Associates the new virtual disk with an existing virtual disk. - /// If this parameter is not NULL, SourcePath must be NULL. - /// - public string ParentPath; - - /// - /// Optional path to pre-populate the new virtual disk object with block data from an existing disk. This path may refer to a VHD or a physical disk. - /// If this parameter is not NULL, ParentPath must be NULL. - /// - public string SourcePath; - - /// - /// Flags for opening the VHD - /// - public OpenVirtualDiskFlags OpenFlags; - - /// - /// GetInfoOnly flag for V2 handles - /// - public bool GetInfoOnly; - - /// - /// Virtual Storage Type of the parent disk - /// - public VirtualStorageType ParentVirtualStorageType; - - /// - /// Virtual Storage Type of the source disk - /// - public VirtualStorageType SourceVirtualStorageType; - - /// - /// A GUID to use for fallback resiliency over SMB. - /// - public Guid ResiliencyGuid; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct VirtualStorageType - { - public VirtualStorageDeviceType DeviceId; - public Guid VendorId; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct SecurityDescriptor - { - public byte revision; - public byte size; - public short control; - public IntPtr owner; - public IntPtr group; - public IntPtr sacl; - public IntPtr dacl; - } - - #endregion Structs - - #region VirtDisk.DLL P/Invoke - - [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)] - public static extern uint - CreateVirtualDisk( - [In, Out] ref VirtualStorageType VirtualStorageType, - [In] string Path, - [In] VirtualDiskAccessMask VirtualDiskAccessMask, - [In, Out] ref SecurityDescriptor SecurityDescriptor, - [In] CreateVirtualDiskFlags Flags, - [In] uint ProviderSpecificFlags, - [In, Out] ref CreateVirtualDiskParameters Parameters, - [In] IntPtr Overlapped, - [Out] out SafeFileHandle Handle); - - #endregion VirtDisk.DLL P/Invoke - - #region Win32 P/Invoke - - [DllImport("advapi32", SetLastError = true)] - public static extern bool InitializeSecurityDescriptor( - [Out] out SecurityDescriptor pSecurityDescriptor, - [In] uint dwRevision); - - #endregion Win32 P/Invoke - - #region WIMGAPI P/Invoke - - #region SafeHandle wrappers for WimFileHandle and WimImageHandle - - public sealed class WimFileHandle : SafeHandle - { - - public WimFileHandle( - string wimPath) - : base(IntPtr.Zero, true) - { - - if (String.IsNullOrEmpty(wimPath)) - { - throw new ArgumentNullException("wimPath"); - } - - if (!File.Exists(Path.GetFullPath(wimPath))) - { - throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath); - } - - NativeMethods.WimCreationResult creationResult; - - this.handle = NativeMethods.WimCreateFile( - wimPath, - NativeMethods.WimCreateFileDesiredAccess.WimGenericRead, - NativeMethods.WimCreationDisposition.WimOpenExisting, - NativeMethods.WimActionFlags.WimIgnored, - NativeMethods.WimCompressionType.WimIgnored, - out creationResult - ); - - // Check results. - if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting) - { - throw new Win32Exception(); - } - - if (this.handle == IntPtr.Zero) - { - throw new Win32Exception(); - } - - // Set the temporary path. - NativeMethods.WimSetTemporaryPath( - this, - Environment.ExpandEnvironmentVariables("%TEMP%") - ); - } - - protected override bool ReleaseHandle() - { - return NativeMethods.WimCloseHandle(this.handle); - } - - public override bool IsInvalid - { - get { return this.handle == IntPtr.Zero; } - } - } - - public sealed class WimImageHandle : SafeHandle - { - public WimImageHandle( - WimFile Container, - uint ImageIndex) - : base(IntPtr.Zero, true) - { - - if (null == Container) - { - throw new ArgumentNullException("Container"); - } - - if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) - { - throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container"); - } - - if (ImageIndex > Container.ImageCount) - { - throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file."); - } - - this.handle = NativeMethods.WimLoadImage( - Container.Handle.DangerousGetHandle(), - ImageIndex); - } - - protected override bool ReleaseHandle() - { - return NativeMethods.WimCloseHandle(this.handle); - } - - public override bool IsInvalid - { - get { return this.handle == IntPtr.Zero; } - } - } - - #endregion SafeHandle wrappers for WimFileHandle and WimImageHandle - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")] - internal static extern IntPtr - WimCreateFile( - [In, MarshalAs(UnmanagedType.LPWStr)] string WimPath, - [In] WimCreateFileDesiredAccess DesiredAccess, - [In] WimCreationDisposition CreationDisposition, - [In] WimActionFlags FlagsAndAttributes, - [In] WimCompressionType CompressionType, - [Out, Optional] out WimCreationResult CreationResult - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool - WimCloseHandle( - [In] IntPtr Handle - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")] - internal static extern IntPtr - WimLoadImage( - [In] IntPtr Handle, - [In] uint ImageIndex - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")] - internal static extern uint - WimGetImageCount( - [In] WimFileHandle Handle - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool - WimGetImageInformation( - [In] SafeHandle Handle, - [Out] out StringBuilder ImageInfo, - [Out] out uint SizeOfImageInfo - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool - WimSetTemporaryPath( - [In] WimFileHandle Handle, - [In] string TempPath - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)] - internal static extern uint - WimRegisterMessageCallback( - [In, Optional] WimFileHandle hWim, - [In] WimMessageCallback MessageProc, - [In, Optional] IntPtr ImageInfo - ); - - [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool - WimUnregisterMessageCallback( - [In, Optional] WimFileHandle hWim, - [In] WimMessageCallback MessageProc - ); - - - #endregion WIMGAPI P/Invoke -} - -#region WIM Interop - -public class WimFile -{ - - internal XDocument m_xmlInfo; - internal List m_imageList; - - private static NativeMethods.WimMessageCallback wimMessageCallback; - - #region Events - - /// - /// DefaultImageEvent handler - /// - public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e); - - /// - ///ProcessFileEvent handler - /// - public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e); - - /// - ///Enable the caller to prevent a file resource from being compressed during a capture. - /// - public event ProcessFileEventHandler ProcessFileEvent; - - /// - ///Indicate an update in the progress of an image application. - /// - public event DefaultImageEventHandler ProgressEvent; - - /// - ///Alert the caller that an error has occurred while capturing or applying an image. - /// - public event DefaultImageEventHandler ErrorEvent; - - /// - ///Indicate that a file has been either captured or applied. - /// - public event DefaultImageEventHandler StepItEvent; - - /// - ///Indicate the number of files that will be captured or applied. - /// - public event DefaultImageEventHandler SetRangeEvent; - - /// - ///Indicate the number of files that have been captured or applied. - /// - public event DefaultImageEventHandler SetPosEvent; - - #endregion Events - - private - enum - ImageEventMessage : uint - { - /// - ///Enables the caller to prevent a file or a directory from being captured or applied. - /// - Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS, - /// - ///Notification sent to enable the caller to prevent a file or a directory from being captured or applied. - ///To prevent a file or a directory from being captured or applied, call WindowsImageContainer.SkipFile(). - /// - Process = NativeMethods.WimMessage.WIM_MSG_PROCESS, - /// - ///Enables the caller to prevent a file resource from being compressed during a capture. - /// - Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS, - /// - ///Alerts the caller that an error has occurred while capturing or applying an image. - /// - Error = NativeMethods.WimMessage.WIM_MSG_ERROR, - /// - ///Enables the caller to align a file resource on a particular alignment boundary. - /// - Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT, - /// - ///Enables the caller to align a file resource on a particular alignment boundary. - /// - Split = NativeMethods.WimMessage.WIM_MSG_SPLIT, - /// - ///Indicates that volume information is being gathered during an image capture. - /// - Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING, - /// - ///Indicates the number of files that will be captured or applied. - /// - SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE, - /// - ///Indicates the number of files that have been captured or applied. - /// - SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS, - /// - ///Indicates that a file has been either captured or applied. - /// - StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT, - /// - ///Success. - /// - Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS, - /// - ///Abort. - /// - Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE - } - - /// - ///Event callback to the Wimgapi events - /// - private - uint - ImageEventMessagePump( - uint MessageId, - IntPtr wParam, - IntPtr lParam, - IntPtr UserData) - { - - uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS; - - DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData); - - switch ((ImageEventMessage)MessageId) - { - - case ImageEventMessage.Progress: - ProgressEvent(this, eventArgs); - break; - - case ImageEventMessage.Process: - if (null != ProcessFileEvent) - { - string fileToImage = Marshal.PtrToStringUni(wParam); - ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam); - ProcessFileEvent(this, fileToProcess); - - if (fileToProcess.Abort == true) - { - status = (uint)ImageEventMessage.Abort; - } - } - break; - - case ImageEventMessage.Error: - if (null != ErrorEvent) - { - ErrorEvent(this, eventArgs); - } - break; - - case ImageEventMessage.SetRange: - if (null != SetRangeEvent) - { - SetRangeEvent(this, eventArgs); - } - break; - - case ImageEventMessage.SetPos: - if (null != SetPosEvent) - { - SetPosEvent(this, eventArgs); - } - break; - - case ImageEventMessage.StepIt: - if (null != StepItEvent) - { - StepItEvent(this, eventArgs); - } - break; - - default: - break; - } - return status; - - } - - /// - /// Constructor. - /// - /// Path to the WIM container. - public - WimFile(string wimPath) - { - if (string.IsNullOrEmpty(wimPath)) - { - throw new ArgumentNullException("wimPath"); - } - - if (!File.Exists(Path.GetFullPath(wimPath))) - { - throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath); - } - - Handle = new NativeMethods.WimFileHandle(wimPath); - - // Hook up the events before we return. - //wimMessageCallback = new NativeMethods.WimMessageCallback(ImageEventMessagePump); - //NativeMethods.RegisterMessageCallback(this.Handle, wimMessageCallback); - } - - /// - /// Closes the WIM file. - /// - public void - Close() - { - foreach (WimImage image in Images) - { - image.Close(); - } - - if (null != wimMessageCallback) - { - NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback); - wimMessageCallback = null; - } - - if ((!Handle.IsClosed) && (!Handle.IsInvalid)) - { - Handle.Close(); - } - } - - /// - /// Provides a list of WimImage objects, representing the images in the WIM container file. - /// - public List - Images - { - get - { - if (null == m_imageList) - { - - int imageCount = (int)ImageCount; - m_imageList = new List(imageCount); - for (int i = 0; i < imageCount; i++) - { - - // Load up each image so it's ready for us. - m_imageList.Add( - new WimImage(this, (uint)i + 1)); - } - } - - return m_imageList; - } - } - - /// - /// Provides a list of names of the images in the specified WIM container file. - /// - public List - ImageNames - { - get - { - List nameList = new List(); - foreach (WimImage image in Images) - { - nameList.Add(image.ImageName); - } - return nameList; - } - } - - /// - /// Indexer for WIM images inside the WIM container, indexed by the image number. - /// The list of Images is 0-based, but the WIM container is 1-based, so we automatically compensate for that. - /// this[1] returns the 0th image in the WIM container. - /// - /// The 1-based index of the image to retrieve. - /// WinImage object. - public WimImage - this[int ImageIndex] - { - get { return Images[ImageIndex - 1]; } - } - - /// - /// Indexer for WIM images inside the WIM container, indexed by the image name. - /// WIMs created by different processes sometimes contain different information - including the name. - /// Some images have their name stored in the Name field, some in the Flags field, and some in the EditionID field. - /// We take all of those into account in while searching the WIM. - /// - /// - /// - public WimImage - this[string ImageName] - { - get - { - return - Images.Where(i => ( - i.ImageName.ToUpper() == ImageName.ToUpper() || - i.ImageFlags.ToUpper() == ImageName.ToUpper() )) - .DefaultIfEmpty(null) - .FirstOrDefault(); - } - } - - /// - /// Returns the number of images in the WIM container. - /// - internal uint - ImageCount - { - get { return NativeMethods.WimGetImageCount(Handle); } - } - - /// - /// Returns an XDocument representation of the XML metadata for the WIM container and associated images. - /// - internal XDocument - XmlInfo - { - get - { - - if (null == m_xmlInfo) - { - StringBuilder builder; - uint bytes; - if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) - { - throw new Win32Exception(); - } - - // Ensure the length of the returned bytes to avoid garbage characters at the end. - int charCount = (int)bytes / sizeof(char); - if (null != builder) - { - // Get rid of the unicode file marker at the beginning of the XML. - builder.Remove(0, 1); - builder.EnsureCapacity(charCount - 1); - builder.Length = charCount - 1; - - // This isn't likely to change while we have the image open, so cache it. - m_xmlInfo = XDocument.Parse(builder.ToString().Trim()); - } - else - { - m_xmlInfo = null; - } - } - - return m_xmlInfo; - } - } - - public NativeMethods.WimFileHandle Handle - { - get; - private set; - } -} - -public class -WimImage -{ - - internal XDocument m_xmlInfo; - - public - WimImage( - WimFile Container, - uint ImageIndex) - { - - if (null == Container) - { - throw new ArgumentNullException("Container"); - } - - if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) - { - throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container"); - } - - if (ImageIndex > Container.ImageCount) - { - throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file."); - } - - Handle = new NativeMethods.WimImageHandle(Container, ImageIndex); - } - - public enum - Architectures : uint - { - x86 = 0x0, - ARM = 0x5, - IA64 = 0x6, - AMD64 = 0x9, - ARM64 = 0xC - } - - public void - Close() - { - if ((!Handle.IsClosed) && (!Handle.IsInvalid)) - { - Handle.Close(); - } - } - - public NativeMethods.WimImageHandle - Handle - { - get; - private set; - } - - internal XDocument - XmlInfo - { - get - { - - if (null == m_xmlInfo) - { - StringBuilder builder; - uint bytes; - if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) - { - throw new Win32Exception(); - } - - // Ensure the length of the returned bytes to avoid garbage characters at the end. - int charCount = (int)bytes / sizeof(char); - if (null != builder) - { - // Get rid of the unicode file marker at the beginning of the XML. - builder.Remove(0, 1); - builder.EnsureCapacity(charCount - 1); - builder.Length = charCount - 1; - - // This isn't likely to change while we have the image open, so cache it. - m_xmlInfo = XDocument.Parse(builder.ToString().Trim()); - } - else - { - m_xmlInfo = null; - } - } - - return m_xmlInfo; - } - } - - public string - ImageIndex - { - get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; } - } - - public string - ImageName - { - get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; } - } - - public string - ImageEditionId - { - get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; } - } - - public string - ImageFlags - { - get - { - string flagValue = String.Empty; - - try - { - flagValue = XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value; - } - catch - { - - // Some WIM files don't contain a FLAGS element in the metadata. - // In an effort to support those WIMs too, inherit the EditionId if there - // are no Flags. - - if (String.IsNullOrEmpty(flagValue)) - { - flagValue = this.ImageEditionId; - - // Check to see if the EditionId is "ServerHyper". If so, - // tweak it to be "ServerHyperCore" instead. - - if (0 == String.Compare("serverhyper", flagValue, true)) - { - flagValue = "ServerHyperCore"; - } - } - - } - - return flagValue; - } - } - - public string - ImageProductType - { - get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value; } - } - - public string - ImageInstallationType - { - get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; } - } - - public string - ImageDescription - { - get { return XmlInfo.XPathSelectElement("/IMAGE/DESCRIPTION").Value; } - } - - public ulong - ImageSize - { - get { return ulong.Parse(XmlInfo.XPathSelectElement("/IMAGE/TOTALBYTES").Value); } - } - - public Architectures - ImageArchitecture - { - get - { - int arch = -1; - try - { - arch = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/ARCH").Value); - } - catch { } - - return (Architectures)arch; - } - } - - public string - ImageDefaultLanguage - { - get - { - string lang = null; - try - { - lang = XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/LANGUAGES/DEFAULT").Value; - } - catch { } - - return lang; - } - } - - public Version - ImageVersion - { - get - { - int major = 0; - int minor = 0; - int build = 0; - int revision = 0; - - try - { - major = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MAJOR").Value); - minor = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MINOR").Value); - build = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/BUILD").Value); - revision = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/SPBUILD").Value); - } - catch { } - - return (new Version(major, minor, build, revision)); - } - } - - public string - ImageDisplayName - { - get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYNAME").Value; } - } - - public string - ImageDisplayDescription - { - get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYDESCRIPTION").Value; } - } -} - -/// -///Describes the file that is being processed for the ProcessFileEvent. -/// -public class -DefaultImageEventArgs : EventArgs -{ - /// - ///Default constructor. - /// - public - DefaultImageEventArgs( - IntPtr wideParameter, - IntPtr leftParameter, - IntPtr userData) - { - - WideParameter = wideParameter; - LeftParameter = leftParameter; - UserData = userData; - } - - /// - ///wParam - /// - public IntPtr WideParameter - { - get; - private set; - } - - /// - ///lParam - /// - public IntPtr LeftParameter - { - get; - private set; - } - - /// - ///UserData - /// - public IntPtr UserData - { - get; - private set; - } -} - -/// -///Describes the file that is being processed for the ProcessFileEvent. -/// -public class -ProcessFileEventArgs : EventArgs -{ - /// - ///Default constructor. - /// - ///Fully qualified path and file name. For example: c:\file.sys. - ///Default is false - skip file and continue. - ///Set to true to abort the entire image capture. - public - ProcessFileEventArgs( - string file, - IntPtr skipFileFlag) - { - - m_FilePath = file; - m_SkipFileFlag = skipFileFlag; - } - - /// - ///Skip file from being imaged. - /// - public void - SkipFile() - { - byte[] byteBuffer = - { - 0 - }; - int byteBufferSize = byteBuffer.Length; - Marshal.Copy(byteBuffer, 0, m_SkipFileFlag, byteBufferSize); - } - - /// - ///Fully qualified path and file name. - /// - public string - FilePath - { - get - { - string stringToReturn = ""; - if (m_FilePath != null) - { - stringToReturn = m_FilePath; - } - return stringToReturn; - } - } - - /// - ///Flag to indicate if the entire image capture should be aborted. - ///Default is false - skip file and continue. Setting to true will - ///abort the entire image capture. - /// - public bool Abort - { - set { m_Abort = value; } - get { return m_Abort; } - } - - private string m_FilePath; - private bool m_Abort; - private IntPtr m_SkipFileFlag; - -} - -#endregion WIM Interop - -#region VHD Interop -// Based on code written by the Hyper-V Test team. -/// -/// The Virtual Hard Disk class provides methods for creating and manipulating Virtual Hard Disk files. -/// -public class -VirtualHardDisk -{ - #region Static Methods - - #region Sparse Disks - - /// - /// Abbreviated signature of CreateSparseDisk so it's easier to use from WIM2VHD. - /// - /// The type of disk to create, VHD or VHDX. - /// The path of the disk to create. - /// The maximum size of the disk to create. - /// Overwrite the VHD if it already exists. - public static void - CreateSparseDisk( - NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType, - string path, - ulong size, - bool overwrite) - { - - CreateSparseDisk( - path, - size, - overwrite, - null, - IntPtr.Zero, - (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD) - ? NativeMethods.DEFAULT_BLOCK_SIZE - : 0, - virtualStorageDeviceType, - NativeMethods.DISK_SECTOR_SIZE); - } - - /// - /// Creates a new sparse (dynamically expanding) virtual hard disk (.vhd). Supports both sync and async modes. - /// The VHD image file uses only as much space on the backing store as needed to store the actual data the VHD currently contains. - /// - /// The path and name of the VHD to create. - /// The size of the VHD to create in bytes. - /// When creating this type of VHD, the VHD API does not test for free space on the physical backing store based on the maximum size requested, - /// therefore it is possible to successfully create a dynamic VHD with a maximum size larger than the available physical disk free space. - /// The maximum size of a dynamic VHD is 2,040 GB. The minimum size is 3 MB. - /// Optional path to pre-populate the new virtual disk object with block data from an existing disk - /// This path may refer to a VHD or a physical disk. Use NULL if you don't want a source. - /// If the VHD exists, setting this parameter to 'True' will delete it and create a new one. - /// If not null, the operation runs in async mode - /// Block size for the VHD. - /// VHD format version (VHD1 or VHD2) - /// Sector size for the VHD. - /// Thrown when an invalid size is specified - /// Thrown when source VHD is not found. - /// Thrown when there was an error while creating the default security descriptor. - /// Thrown when an error occurred while creating the VHD. - public static void - CreateSparseDisk( - string path, - ulong size, - bool overwrite, - string source, - IntPtr overlapped, - uint blockSizeInBytes, - NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType, - uint sectorSizeInBytes) - { - - // Validate the virtualStorageDeviceType - if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX) - { - - throw ( - new ArgumentOutOfRangeException( - "virtualStorageDeviceType", - virtualStorageDeviceType, - "VirtualStorageDeviceType must be VHD or VHDX." - )); - } - - // Validate size. It needs to be a multiple of DISK_SECTOR_SIZE (512)... - if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0) - { - - throw ( - new ArgumentOutOfRangeException( - "size", - size, - "The size of the virtual disk must be a multiple of 512." - )); - } - - if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source))) - { - - throw ( - new System.IO.FileNotFoundException( - "Unable to find the source file.", - source - )); - } - - if ((overwrite) && (System.IO.File.Exists(path))) - { - - System.IO.File.Delete(path); - } - - NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters(); - - // Select the correct version. - createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD) - ? NativeMethods.CreateVirtualDiskVersion.Version1 - : NativeMethods.CreateVirtualDiskVersion.Version2; - - createParams.UniqueId = Guid.NewGuid(); - createParams.MaximumSize = size; - createParams.BlockSizeInBytes = blockSizeInBytes; - createParams.SectorSizeInBytes = sectorSizeInBytes; - createParams.ParentPath = null; - createParams.SourcePath = source; - createParams.OpenFlags = NativeMethods.OpenVirtualDiskFlags.None; - createParams.GetInfoOnly = false; - createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType(); - createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType(); - - // - // Create and init a security descriptor. - // Since we're creating an essentially blank SD to use with CreateVirtualDisk - // the VHD will take on the security values from the parent directory. - // - - NativeMethods.SecurityDescriptor securityDescriptor; - if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) - { - - throw ( - new SecurityException( - "Unable to initialize the security descriptor for the virtual disk." - )); - } - - NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType(); - virtualStorageType.DeviceId = virtualStorageDeviceType; - virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft; - - SafeFileHandle vhdHandle; - - uint returnCode = NativeMethods.CreateVirtualDisk( - ref virtualStorageType, - path, - (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD) - ? NativeMethods.VirtualDiskAccessMask.All - : NativeMethods.VirtualDiskAccessMask.None, - ref securityDescriptor, - NativeMethods.CreateVirtualDiskFlags.None, - 0, - ref createParams, - overlapped, - out vhdHandle); - - vhdHandle.Close(); - - if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode) - { - - throw ( - new Win32Exception( - (int)returnCode - )); - } - } - - #endregion Sparse Disks - - #endregion Static Methods - -} -#endregion VHD Interop -} -"@ - #ifdef for Powershell V7 or greater which looks for assemblies in same path as powershell dll path - if ($PSVersionTable.psversion.Major -ge 7){ - Add-Type -TypeDefinition $code -ErrorAction SilentlyContinue - } - else { - Add-Type -TypeDefinition $code -ReferencedAssemblies "System.Xml","System.Linq","System.Xml.Linq" -ErrorAction SilentlyContinue - } -} - -Function Modify-AutoUnattend { -param ( -[string]$username, -[string]$password, -[string]$autologon, -[string]$hostname, -[string]$UnattendPath - ) - [xml]$xml = get-content -path $UnattendPath - ($xml.unattend.settings.component | where-object {$_.autologon}).autologon.password.value = $password - ($xml.unattend.settings.component | where-object {$_.autologon}).autologon.username = $username - ($xml.unattend.settings.component | where-object {$_.autologon}).autologon.enabled = $autologon - ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.Group = "Administrators" - ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.Name = $username - ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.DisplayName = $username - ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.Password.Value = $password - ($xml.unattend.settings.component | where-object {$_.Computername}).Computername = $hostname - $xml.Save("$UnattendPath") -} - -function Assign-VMGPUPartitionAdapter { -param( -[string]$VMName, -[string]$GPUName, -[decimal]$GPUResourceAllocationPercentage = 100 -) - - $PartitionableGPUList = Get-WmiObject -Class "Msvm_PartitionableGpu" -ComputerName $env:COMPUTERNAME -Namespace "ROOT\virtualization\v2" - if ($GPUName -eq "AUTO") { - $DevicePathName = $PartitionableGPUList.Name[0] - Add-VMGpuPartitionAdapter -VMName $VMName - } - else { - $DeviceID = ((Get-WmiObject Win32_PNPSignedDriver | where {($_.Devicename -eq "$GPUNAME")}).hardwareid).split('\')[1] - $DevicePathName = ($PartitionableGPUList | Where-Object name -like "*$deviceid*").Name - Add-VMGpuPartitionAdapter -VMName $VMName -InstancePath $DevicePathName - } - - [float]$devider = [math]::round($(100 / $GPUResourceAllocationPercentage),2) - - Set-VMGpuPartitionAdapter -VMName $VMName -MinPartitionVRAM ([math]::round($(1000000000 / $devider))) -MaxPartitionVRAM ([math]::round($(1000000000 / $devider))) -OptimalPartitionVRAM ([math]::round($(1000000000 / $devider))) - Set-VMGPUPartitionAdapter -VMName $VMName -MinPartitionEncode ([math]::round($(18446744073709551615 / $devider))) -MaxPartitionEncode ([math]::round($(18446744073709551615 / $devider))) -OptimalPartitionEncode ([math]::round($(18446744073709551615 / $devider))) - Set-VMGpuPartitionAdapter -VMName $VMName -MinPartitionDecode ([math]::round($(1000000000 / $devider))) -MaxPartitionDecode ([math]::round($(1000000000 / $devider))) -OptimalPartitionDecode ([math]::round($(1000000000 / $devider))) - Set-VMGpuPartitionAdapter -VMName $VMName -MinPartitionCompute ([math]::round($(1000000000 / $devider))) -MaxPartitionCompute ([math]::round($(1000000000 / $devider))) -OptimalPartitionCompute ([math]::round($(1000000000 / $devider))) - -} - -Function New-GPUEnabledVM { -param( -[int64]$SizeBytes, -[int]$Edition, -[string]$VhdFormat, -[string]$VhdPath, -[string]$VMName, -[string]$DiskLayout, -[string]$UnattendPath, -[int64]$MemoryAmount, -[int]$CPUCores, -[string]$NetworkSwitch, -[string]$GPUName, -[float]$GPUResourceAllocationPercentage, -[string]$SourcePath, -[string]$Team_ID, -[string]$Key, -[string]$username, -[string]$password, -[string]$autologon -) - $VHDPath = ConcatenateVHDPath -VHDPath $VHDPath -VMName $VMName - $DriveLetter = Mount-ISOReliable -SourcePath $SourcePath - - if ($(Get-VM -Name $VMName -ErrorAction SilentlyContinue) -ne $NULL) { - SmartExit -ExitReason "Virtual Machine already exists with name $VMName, please delete existing VM or change VMName" - } - if (Test-Path $vhdPath) { - SmartExit -ExitReason "Virtual Machine Disk already exists at $vhdPath, please delete existing VHDX or change VMName" - } - Modify-AutoUnattend -username "$username" -password "$password" -autologon $autologon -hostname $VMName -UnattendPath $UnattendPath - $MaxAvailableVersion = (Get-VMHostSupportedVersion).Version | Where-Object {$_.Major -lt 254}| Select-Object -Last 1 - Convert-WindowsImage -SourcePath $SourcePath -ISODriveLetter $DriveLetter -Edition $Edition -VHDFormat $Vhdformat -VHDPath $VhdPath -DiskLayout $DiskLayout -UnattendPath $UnattendPath -GPUName $GPUName -Team_ID $Team_ID -Key $Key -SizeBytes $SizeBytes| Out-Null - if (Test-Path $vhdPath) { - New-VM -Name $VMName -MemoryStartupBytes $MemoryAmount -VHDPath $VhdPath -Generation 2 -SwitchName $NetworkSwitch -Version $MaxAvailableVersion | Out-Null - Set-VM -Name $VMName -ProcessorCount $CPUCores -CheckpointType Disabled -LowMemoryMappedIoSpace 3GB -HighMemoryMappedIoSpace 32GB -GuestControlledCacheTypes $true -AutomaticStopAction ShutDown - Set-VMMemory -VMName $VMName -DynamicMemoryEnabled $false - $CPUManufacturer = Get-CimInstance -ClassName Win32_Processor | Foreach-Object Manufacturer - $BuildVer = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - if (($BuildVer.CurrentBuild -lt 22000) -and ($CPUManufacturer -eq "AuthenticAMD")) { - } - Else { - Set-VMProcessor -VMName $VMName -ExposeVirtualizationExtensions $true - } - Set-VMHost -ComputerName $ENV:Computername -EnableEnhancedSessionMode $false - Set-VMVideo -VMName $VMName -HorizontalResolution 1920 -VerticalResolution 1080 - Set-VMKeyProtector -VMName $VMName -NewLocalKeyProtector - Enable-VMTPM -VMName $VMName - Add-VMDvdDrive -VMName $VMName -Path $SourcePath - Assign-VMGPUPartitionAdapter -GPUName $GPUName -VMName $VMName -GPUResourceAllocationPercentage $GPUResourceAllocationPercentage - Write-Host "INFO : Starting and connecting to VM" - vmconnect localhost $VMName - } - else { - SmartExit -ExitReason "Failed to create VHDX, stopping script" - } -} - -Check-Params @params - -New-GPUEnabledVM @params - -Start-VM -Name $params.VMName - -SmartExit -ExitReason "If all went well the Virtual Machine will have started, -In a few minutes it will load the Windows desktop, -when it does, sign into Parsec (a fast remote desktop app) -and connect to the machine using Parsec from another computer. -Have fun! -Sign up to Parsec at https://parsec.app" diff --git a/GPUP-management.ps1 b/GPUP-management.ps1 new file mode 100644 index 0000000..4383967 --- /dev/null +++ b/GPUP-management.ps1 @@ -0,0 +1,4310 @@ +#======================================================================== +$Global:VM +$Global:VHD +$Global:ServerOS +$Global:StateWasRunning +#======================================================================== + +#======================================================================== +$params = @{ + GPUName = "" + DriveLetter = "" + GPUDedicatedResourcePercentage = 100 + VMName = "" + SourcePath = "" + Edition = "" + VhdFormat = "VHDX" + DiskLayout = "UEFI" + SizeBytes = 127GB + MemoryAmount = 4GB + MemoryMaximum = 32GB + DynamicMemoryEnabled = $true + CPUCores = 4 + NetworkSwitch = "Default Switch" + VMPath = "" + VHDPath = "" + Team_ID = "" + Key = "" + Username = "" + Password = "" + Autologon = $true + RDP = $true + Parsec = $true + CopyRegionalSettings = $true + ParsecVDD = $false + DisableHVDD = $false + NumLock = $true +} +#======================================================================== + +#======================================================================== +[xml]$unattend = @" + + + + + + en-US + + 0409:00000409 + en-US + en-US + en-US + en-US + + + + + 0 + true + + + + 1 + Primary + 300 + + + + 2 + EFI + 100 + + + + 3 + MSR + 128 + + + + 4 + Primary + true + + + + + + 1 + 1 + + NTFS + DE94BBA4-06D1-4D40-A16A-BFD50179D6AC + + + + 2 + 2 + + FAT32 + + + + 3 + 3 + + + + 4 + 4 + + C + NTFS + + + + + + + + 0 + 4 + + false + + + + + + + + + Never + + true + GPU-P + + + + + + + + true + + + + + 1 + + + + + 0409:00000409 + en-US + en-US + en-US + en-US + + + true + + + 0 + + + GPUP122 + W269N-WFGWX-YVC9B-4J6C9-T83GX + + + + + + + CoolestPassword! + true</PlainText> + </Password> + <Enabled>true</Enabled> + <Username>GPUVM</Username> + </AutoLogon> + <OOBE> + <HideEULAPage>true</HideEULAPage> + <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen> + <HideOnlineAccountScreens>true</HideOnlineAccountScreens> + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> + <NetworkLocation>Home</NetworkLocation> + <SkipUserOOBE>true</SkipUserOOBE> + <SkipMachineOOBE>true</SkipMachineOOBE> + <ProtectYourPC>1</ProtectYourPC> + </OOBE> + <Display> + <ColorDepth>32</ColorDepth> + <HorizontalResolution>1920</HorizontalResolution> + <RefreshRate>60</RefreshRate> + <VerticalResolution>1080</VerticalResolution> + </Display> + <UserAccounts> + <LocalAccounts> + <LocalAccount wcm:action="add"> + <Password> + <Value>CoolestPassword!</Value> + <PlainText>true</PlainText> + </Password> + <Description> + </Description> + <DisplayName>GPUVM</DisplayName> + <Group>Administrators</Group> + <Name>GPUVM</Name> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + <RegisteredOrganization> + </RegisteredOrganization> + <RegisteredOwner>GPU-P</RegisteredOwner> + <DisableAutoDaylightTimeSet>false</DisableAutoDaylightTimeSet> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Description>Allow Scripts</Description> + <Order>1</Order> + <CommandLine>reg add HKLM\Software\Policies\Microsoft\Windows\Powershell</CommandLine> + <RequiresUserInput>false</RequiresUserInput> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Description>Allow Scripts</Description> + <Order>2</Order> + <CommandLine>reg add HKLM\Software\Policies\Microsoft\Windows\Powershell /v ExecutionPolicy /t REG_SZ /d Unrestricted</CommandLine> + <RequiresUserInput>false</RequiresUserInput> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Description>Allow Scripts</Description> + <Order>3</Order> + <CommandLine>reg add HKLM\Software\Policies\Microsoft\Windows\Powershell /v EnableScripts /t REG_DWORD /d 1</CommandLine> + <RequiresUserInput>false</RequiresUserInput> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>4</Order> + <RequiresUserInput>false</RequiresUserInput> + <CommandLine>cmd /C wmic useraccount where name="GPU-P" set PasswordExpires=false</CommandLine> + <Description>Password Never Expires</Description> + </SynchronousCommand> + </FirstLogonCommands> + <TimeZone>GTB Standard Time</TimeZone> + </component> + </settings> +</unattend> +"@ +#======================================================================== + +#======================================================================== +$ParsecLnk = ( + 31, 139, 8, 0, 0, 0, 0, 0, 0, 10, 237, 85, 95, 72, 83, 97, 20, 63, 179, 85, 46, 77, 39, 91, 98, 86, 186, 210, 201, 178, 156, 155, 210, 191, 129, + 53, 81, 116, 90, 185, 235, 102, 217, 195, 165, 156, 219, 77, 23, 51, 215, 238, 130, 65, 80, 20, 244, 16, 44, 48, 168, 160, 208, 208, 176, 36, 208, 7, 19, 21, + 31, 76, 133, 210, 183, 24, 138, 253, 51, 194, 215, 140, 16, 95, 194, 222, 58, 231, 219, 157, 179, 165, 152, 208, 147, 244, 93, 206, 249, 190, 123, 254, 254, 190, 243, + 125, 231, 222, 83, 0, 32, 83, 199, 33, 7, 24, 101, 28, 202, 102, 204, 241, 160, 161, 85, 246, 228, 227, 19, 227, 211, 178, 92, 197, 181, 195, 159, 39, 166, 101, + 145, 119, 75, 226, 22, 102, 40, 11, 219, 47, 141, 43, 50, 53, 100, 114, 179, 214, 144, 102, 206, 228, 86, 62, 253, 16, 15, 7, 12, 134, 182, 157, 144, 95, 98, + 226, 99, 76, 105, 4, 193, 200, 230, 60, 78, 61, 156, 2, 156, 205, 90, 110, 43, 190, 142, 34, 63, 40, 64, 14, 243, 175, 196, 170, 135, 57, 164, 211, 163, 77, + 95, 134, 252, 183, 132, 149, 140, 203, 191, 42, 129, 3, 31, 52, 67, 3, 114, 7, 52, 33, 236, 50, 112, 131, 7, 4, 16, 81, 111, 70, 222, 136, 107, 15, 62, + 133, 80, 0, 122, 112, 177, 245, 65, 200, 195, 55, 35, 28, 129, 163, 12, 67, 26, 212, 72, 88, 244, 92, 109, 11, 198, 116, 248, 68, 193, 9, 112, 92, 66, 146, + 203, 85, 5, 73, 67, 72, 78, 247, 109, 71, 30, 46, 88, 116, 140, 157, 173, 69, 36, 14, 68, 33, 98, 62, 116, 133, 84, 168, 199, 28, 84, 42, 29, 215, 122, + 75, 3, 94, 22, 211, 165, 23, 2, 2, 88, 164, 184, 164, 201, 229, 172, 65, 138, 219, 221, 65, 187, 219, 181, 66, 157, 188, 203, 226, 186, 112, 15, 2, 4, 144, + 0, 210, 145, 106, 144, 118, 75, 149, 161, 57, 95, 242, 177, 35, 169, 144, 54, 33, 105, 102, 126, 118, 42, 113, 182, 218, 1, 15, 130, 243, 53, 55, 248, 28, 77, + 154, 50, 183, 71, 16, 249, 240, 78, 249, 229, 224, 88, 157, 244, 192, 175, 193, 87, 175, 59, 233, 162, 136, 249, 85, 240, 167, 65, 9, 152, 214, 21, 39, 107, 221, + 30, 43, 103, 206, 198, 195, 83, 0, 180, 223, 195, 154, 24, 237, 156, 253, 187, 97, 248, 83, 9, 220, 41, 239, 90, 12, 169, 58, 197, 139, 251, 174, 162, 220, 69, + 69, 204, 36, 3, 36, 186, 64, 20, 194, 207, 18, 95, 198, 148, 58, 9, 202, 25, 22, 156, 82, 240, 120, 37, 9, 78, 24, 70, 49, 166, 246, 66, 41, 74, 252, + 72, 60, 216, 208, 143, 180, 110, 244, 110, 136, 129, 185, 127, 233, 160, 123, 36, 64, 134, 5, 237, 224, 124, 121, 186, 242, 217, 66, 92, 93, 240, 201, 183, 110, 178, + 216, 22, 1, 148, 16, 115, 35, 162, 247, 1, 96, 7, 82, 50, 45, 204, 196, 10, 198, 111, 190, 31, 153, 146, 145, 48, 49, 162, 133, 47, 111, 169, 145, 88, 82, + 121, 36, 36, 105, 195, 136, 61, 136, 208, 201, 80, 187, 217, 78, 195, 78, 73, 177, 33, 105, 217, 33, 129, 125, 126, 201, 169, 43, 122, 48, 153, 210, 255, 14, 70, + 173, 31, 211, 66, 183, 81, 158, 17, 137, 108, 66, 250, 119, 149, 226, 255, 56, 9, 126, 213, 82, 0, 28, 147, 0, 246, 166, 54, 149, 246, 220, 245, 90, 186, 44, + 102, 125, 103, 81, 32, 184, 7, 229, 141, 100, 96, 65, 170, 238, 173, 19, 109, 63, 156, 21, 253, 109, 241, 134, 236, 71, 137, 75, 31, 24, 53, 54, 206, 86, 188, + 35, 90, 169, 93, 88, 183, 104, 87, 108, 151, 13, 63, 180, 49, 29, 23, 237, 55, 237, 95, 118, 220, 255, 177, 17, 6, 253, 67, 54, 99, 79, 228, 224, 60, 132, + 68, 255, 27, 252, 26, 181, 15, 56, 207, 183, 140, 140, 85, 85, 188, 108, 21, 6, 11, 166, 38, 211, 73, 87, 135, 132, 45, 212, 126, 78, 242, 13, 120, 197, 60, + 227, 161, 104, 172, 69, 168, 159, 78, 82, 36, 87, 6, 249, 215, 254, 217, 27, 213, 23, 84, 89, 47, 38, 18, 10, 231, 82, 134, 246, 182, 14, 132, 222, 156, 188, + 191, 150, 158, 98, 252, 2, 171, 79, 220, 238, 187, 8, 0, 0 +) +#======================================================================== + +#======================================================================== +function Write-W2VInfo { + # Function to make the Write-Host output a bit prettier. + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [object] + [ValidateNotNullOrEmpty()]$Object, + [bool]$NoNewline, + [Object]$Separator, + [ConsoleColor]$ForegroundColor, + [ConsoleColor]$BackgroundColor + ) + $PSBoundParameters.Object = "INFO: $($Object)" + Write-Host @PSBoundParameters +} +#======================================================================== + +#======================================================================== +function Write-W2VInProgress { + # Function to make the Write-Host output a bit prettier. + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [object] + [ValidateNotNullOrEmpty()]$Object, + [Object]$Separator, + [ConsoleColor]$ForegroundColor, + [ConsoleColor]$BackgroundColor + ) + if ($Global:W2VInProgressCounter++ -eq 10) { $Global:W2VInProgressCounter = 0 } + $PSBoundParameters.NoNewLine = $true + $PSBoundParameters.Object = "$($Object) $(`".`" * $Global:W2VInProgressCounter)" + Write-Host @PSBoundParameters +} +#======================================================================== + +#======================================================================== +function Set-W2VItemProperty { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [string[]]$Path, + [Parameter(Mandatory = $true)] + [string]$Name, + [Parameter(Mandatory = $true)] + [Object]$Value, + [switch]$Force, + [string]$Filter, + [string[]]$Include, + [string[]]$Exclude, + [pscredential]$Credential, + [string]$Type, + [string]$PropertyType, + [object]$CommonParameters + ) + if ((Test-Path $path) -eq $false) { + New-Item $path -Force + } + if ((Get-ItemProperty -path $path -name $Name -ErrorAction SilentlyContinue).Count -eq 0) { + if ($PSBoundParameters.Type.Length -ne 0) { + if ($PSBoundParameters.PropertyType.Length -eq 0) { + $PSBoundParameters.PropertyType = $PSBoundParameters.Type + } + $PSBoundParameters.Remove('Type') + } + $null = New-ItemProperty @PSBoundParameters + } else { + if ($PSBoundParameters.PropertyType.Length -ne 0) { + if ($PSBoundParameters.Type.Length -eq 0) { + $PSBoundParameters.Type = $PSBoundParameters.PropertyType + } + $PSBoundParameters.Remove('PropertyType') + } + $null = Set-ItemProperty @PSBoundParameters + } +} +#======================================================================== + +#======================================================================== +function Is-Administrator { + $CurrentUser = [Security.Principal.WindowsIdentity]::GetCurrent(); + $IsAdmin = (New-Object Security.Principal.WindowsPrincipal $CurrentUser).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) + if ($IsAdmin -eq $false) { + Write-Warning "Administrator rights are required to run the script." + } + return $IsAdmin +} +#======================================================================== + +#======================================================================== +function Get-ISOWindowsEditions { + param ( + [string]$DriveLetter + ) + $WinImages = Get-windowsimage -ImagePath "$($DriveLetter):\sources\install.wim" + if ($WinImages.Count -eq 0) { + return $null + } + Write-Host "Printing Windows editions on the selected disk image... It may take a while..." -ForegroundColor Yellow + $Report = @() + Write-Host "Index Edition" + Write-Host "===== =======" + foreach ($WinImage in $WinImages) { + $curImage=Get-WindowsImage -ImagePath "$($DriveLetter):\sources\install.wim" -Index $WinImage.ImageIndex + $objImage = [PSCustomObject]@{ + Index = $curImage.ImageIndex + Edition = $curImage.ImageName + Version = $curImage.Version + } + Write-Host "$($curImage.ImageIndex): $($curImage.ImageName)" + $Report += $objImage + } + return $Report +} +#======================================================================== + +#======================================================================== +function Dismount-ISO { + param ( + [string]$SourcePath + ) + $disk = Get-Volume | Where-Object {$_.DriveType -eq "CD-ROM"} | select * + Foreach ($d in $disk) { + Dismount-DiskImage -ImagePath $sourcePath -ErrorAction SilentlyContinue + } +} +#======================================================================== + +#======================================================================== +function Mount-ISOReliable { + param ( + [string]$SourcePath + ) + $mountResult = Mount-DiskImage -ImagePath $SourcePath + $delay = 0 + do { + if ($delay -gt 15) { + function Get-NewDriveLetter { + $UsedDriveLetters = ((Get-Volume).DriveLetter) -join "" + do { $DriveLetter = (65..90)| Get-Random | % {[char]$_} } + Until (!$UsedDriveLetters.Contains("$DriveLetter")) + } + $DriveLetter = "$(Get-NewDriveLetter):" + Get-WmiObject -Class Win32_volume | Where-Object {$_.Label -eq "CCCOMA_X64FRE_EN-US_DV9"} | Set-WmiInstance -Arguments @{DriveLetter="$driveletter"} + } + Start-Sleep -s 1 + $delay++ + } until (($mountResult | Get-Volume).DriveLetter -ne $NULL) + return ($mountResult | Get-Volume).DriveLetter +} +#======================================================================== + +#======================================================================== +function ConcatenateVHDPath { + param( + [string]$VHDPath, + [string]$VMName + ) + if ($VHDPath[-1] -eq '\') { + "$($VHDPath)$($VMName)\$($VMName).vhdx" + } else { + "$($VHDPath)\$($VMName)\$($VMName).vhdx" + } +} +#======================================================================== + +#======================================================================== +function SmartExit { + param ( + [switch]$NoHalt, + [string]$ExitReason + ) + Set-PSDebug -Off + if (($host.name -eq 'Windows PowerShell ISE Host') -or ($host.Name -eq 'Visual Studio Code Host')) { + Write-Host $ExitReason + Exit $null + } else{ + if ($NoHalt) { + Write-Host $ExitReason + Exit $null + } else { + Write-Host $ExitReason + Read-host -Prompt "Press any key to Exit..." + Exit $null + } + } +} +#======================================================================== + +#======================================================================== +function New-GPUEnabledVM { + param( + [string]$DriveLetter, + [int64]$SizeBytes, + [int]$Edition, + [string]$VhdFormat, + [string]$VMPath, + [string]$VhdPath, + [string]$VMName, + [string]$DiskLayout, + [int64]$MemoryAmount, + [int64]$MemoryMaximum, + [boolean]$DynamicMemoryEnabled, + [int]$CPUCores, + [string]$NetworkSwitch, + [string]$GPUName, + [float]$GPUDedicatedResourcePercentage, + [string]$SourcePath, + [string]$Team_ID, + [string]$Key, + [string]$username, + [string]$password, + [string]$autologon, + [bool]$RDP, + [bool]$Parsec, + [bool]$CopyRegionalSettings, + [bool]$ParsecVDD, + [bool]$DisableHVDD, + [bool]$NumLock + ) + + $VHDPath = ConcatenateVHDPath -VHDPath $VHDPath -VMName $VMName + + if ($(Get-VM -Name $VMName -ErrorAction SilentlyContinue) -ne $NULL) { + SmartExit -ExitReason "Virtual Machine already exists with name $VMName, please delete existing VM or change VMName" + } + if (Test-Path $vhdPath) { + SmartExit -ExitReason "Virtual Machine Disk already exists at $vhdPath, please delete existing VHDX or change VMName" + } + Write-Host "Virtual Machine is creating... It may take a long time..." -ForegroundColor Yellow + $unattendPath = Modify-AutoUnattend -username "$username" -password "$password" -autologon $autologon -hostname $VMName -CopyRegionalSettings $CopyRegionalSettings -xml $unattend + $MaxAvailableVersion = (Get-VMHostSupportedVersion).Version | Where-Object {$_.Major -lt 254} | Select-Object -Last 1 + Convert-WindowsImage -SourcePath $SourcePath -ISODriveLetter $DriveLetter -Edition $Edition -VHDFormat $Vhdformat -VHDPath $VhdPath -DiskLayout $DiskLayout -UnattendPath $UnattendPath -Parsec:$Parsec -ParsecVDD:$ParsecVDD -DisableHVDD:$DisableHVDD -RDP:$RDP -NumLock:$NumLock -GPUName $GPUName -Team_ID $Team_ID -Key $Key -SizeBytes $SizeBytes | Out-Null + if (Test-Path $vhdPath) { + $Global:VM = New-VM -Name $VMName -MemoryStartupBytes $MemoryAmount -Path $VMPath -VHDPath $VhdPath -Generation 2 -SwitchName $NetworkSwitch -Version $MaxAvailableVersion + $Global:VM | Set-VMMemory -DynamicMemoryEnabled:$DynamicMemoryEnabled + $Global:VM | Set-VM -ProcessorCount $CPUCores + $Global:VM | Set-VM -CheckpointType Disabled + $Global:VM | Set-VM -MemoryMinimum $MemoryAmount + $Global:VM | Set-VM -MemoryMaximum $MemoryMaximum + $Global:VM | Set-VM -LowMemoryMappedIoSpace 3GB + $Global:VM | Set-VM -HighMemoryMappedIoSpace 32GB + $Global:VM | Set-VM -GuestControlledCacheTypes:$true + $Global:VM | Set-VM -AutomaticStopAction ShutDown + $CPUManufacturer = Get-CimInstance -ClassName Win32_Processor | Foreach-Object Manufacturer + $BuildVer = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' + if (($BuildVer.CurrentBuild -lt 22000) -and ($CPUManufacturer -eq "AuthenticAMD")) { + } else { + $Global:VM | Set-VMProcessor -ExposeVirtualizationExtensions $true + } + Set-VMHost -ComputerName $ENV:Computername -EnableEnhancedSessionMode $false + $Global:VM | Set-VMVideo -HorizontalResolution 1920 -VerticalResolution 1080 + $Global:VM | Set-VMKeyProtector -NewLocalKeyProtector + $Global:VM | Enable-VMTPM + $Global:VM | Add-VMDvdDrive -Path $SourcePath + $Global:VHD = $Global:VM | Get-VMHardDiskDrive + Pass-VMGPUPartitionAdapter + Write-W2VInfo "Starting and connecting to VM" + if ($Global:ServerOS -eq $true) { + Set-ServerOSGroupPolicies + } + vmconnect localhost $VMName + } else { + SmartExit -ExitReason "Failed to create VHDX, stopping script" + } +} +#======================================================================== + +#======================================================================== +function Setup-RemoteDesktop { + param( + [Parameter(Mandatory = $true)][bool]$Parsec, + [bool]$ParsecVDD, + [bool]$DisableHVDD, + [Parameter(Mandatory = $true)][bool]$RDP, + [bool]$NumLock, + [Parameter(Mandatory = $true)][string]$DriveLetter, + [string]$Team_ID, + [string]$Key + ) + + if (($Parsec -eq $false) -and ($RDP -eq $false) -and ($NumLock -eq $false)) { + return $null + } + + New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon -ItemType directory -Force | Out-Null + New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logoff -ItemType directory -Force | Out-Null + New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup -ItemType directory -Force | Out-Null + New-Item -Path $DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Shutdown -ItemType directory -Force | Out-Null + New-Item -Path $DriveLetter\ProgramData\Easy-GPU-P -ItemType directory -Force | Out-Null + + $path = "$DriveLetter\Windows\system32\GroupPolicy\User\Scripts\psscripts.ini" + "[Logon]" >> $path + "0CmdLine=Install.ps1" >> $path + "0Parameters=$RDP $Parsec $ParsecVDD $DisableHVDD $NumLock $Team_ID $Key" >> $path + + if ($NumLock -eq $true) { + $path = "$DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\psscripts.ini" + "[Startup]" >> $path + "0CmdLine=NumLockEnable.ps1" >> $path + "0Parameters=" >> $path + + $path = "$DriveLetter\Windows\system32\GroupPolicy\Machine\Scripts\Startup\NumLockEnable.ps1" + "`$WshShell = New-Object -ComObject WScript.Shell" >> $path + "for (`$i=0; `$i -lt 5; `$i++) {" >> $path + " Start-Sleep -s 0.1" >> $path + " if ([console]::NumberLock -eq `$false) {" >> $path + " `$WshShell.SendKeys(`"{NUMLOCK}`")" >> $path + " } else { break }" >> $path + "}" >> $path + } + + $path = "$DriveLetter\Windows\system32\GroupPolicy\gpt.ini" + "[General]" >> $path + "gPCUserExtensionNames=[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B66650-4972-11D1-A7CA-0000F87571E3}]" >> $path + "Version=131074" >> $path + "gPCMachineExtensionNames=[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]" >> $path + + Copy-Item -Path $psscriptroot\VMScripts\Install.ps1 -Destination $DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon + + if ($Parsec -eq $true) { + Copy-Item -Path $psscriptroot\VMScripts\VDDMonitor.ps1 -Destination $DriveLetter\ProgramData\Easy-GPU-P + Copy-Item -Path $psscriptroot\misc\ParsecPublic.cer -Destination $DriveLetter\ProgramData\Easy-GPU-P + $compressedDataStream = New-Object System.IO.MemoryStream + $compressedDataStream.Write($parsecLnk, 0, $parsecLnk.Length) + $compressedDataStream.Position = 0 + $decompressGzipStream = New-Object System.IO.Compression.GZipStream($compressedDataStream, [System.IO.Compression.CompressionMode]::Decompress) + $decompressedStream = New-Object System.IO.MemoryStream + $buffer = New-Object byte[](1024) + while (($read = $decompressGzipStream.Read($buffer, 0, $buffer.Length)) -gt 0) { + $decompressedStream.Write($buffer, 0, $read) + } + $decompressGzipStream.Close() + $decompressedData = $decompressedStream.ToArray() + [io.file]::WriteAllBytes("$DriveLetter\ProgramData\Easy-GPU-P\Parsec.lnk", $decompressedData) + } +} +#======================================================================== + +#======================================================================== +function Convert-WindowsImage { + <# + .NOTES + Copyright (c) Microsoft Corporation. All rights reserved. + Use of this sample source code is subject to the terms of the Microsoft + license agreement under which you licensed this sample source code. If + you did not accept the terms of the license agreement, you are not + authorized to use this sample source code. For the terms of the license, + please see the license agreement between you and Microsoft or, if applicable, + see the LICENSE.RTF on your install media or the root of your tools installation. + THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES. + + .SYNOPSIS + Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media. + + .DESCRIPTION + Creates a bootable VHD(X) based on Windows 7 or Windows 8 installation media. + + .PARAMETER SourcePath + The complete path to the WIM or ISO file that will be converted to a Virtual Hard Disk. + The ISO file must be valid Windows installation media to be recognized successfully. + + .PARAMETER CacheSource + If the source WIM/ISO was copied locally, we delete it by default. + Pass $true to cache the source image from the temp directory. + + .PARAMETER VHDPath + The name and path of the Virtual Hard Disk to create. + Omitting this parameter will create the Virtual Hard Disk is the current directory, (or, + if specified by the -WorkingDirectory parameter, the working directory) and will automatically + name the file in the following format: + + <build>.<revision>.<architecture>.<branch>.<timestamp>_<skufamily>_<sku>_<language>.<extension> + i.e.: + 9200.0.amd64fre.winmain_win8rtm.120725-1247_client_professional_en-us.vhd(x) + + .PARAMETER WorkingDirectory + Specifies the directory where the VHD(X) file should be generated. + If specified along with -VHDPath, the -WorkingDirectory value is ignored. + The default value is the current directory ($pwd). + + .PARAMETER TempDirectory + Specifies the directory where the logs and ISO files should be placed. + The default value is the temp directory ($env:Temp). + + .PARAMETER SizeBytes + The size of the Virtual Hard Disk to create. + For fixed disks, the VHD(X) file will be allocated all of this space immediately. + For dynamic disks, this will be the maximum size that the VHD(X) can grow to. + The default value is 40GB. + + .PARAMETER VHDFormat + Specifies whether to create a VHD or VHDX formatted Virtual Hard Disk. + The default is AUTO, which will create a VHD if using the BIOS disk layout or + VHDX if using UEFI or WindowsToGo layouts. + + .PARAMETER DiskLayout + Specifies whether to build the image for BIOS (MBR), UEFI (GPT), or WindowsToGo (MBR). + Generation 1 VMs require BIOS (MBR) images. Generation 2 VMs require UEFI (GPT) images. + Windows To Go images will boot in UEFI or BIOS but are not technically supported (upgrade + doesn't work) + + .PARAMETER UnattendPath + The complete path to an unattend.xml file that can be injected into the VHD(X). + + .PARAMETER Edition + The name or image index of the image to apply from the WIM. + + .PARAMETER Passthru + Specifies that the full path to the VHD(X) that is created should be + returned on the pipeline. + + .PARAMETER BCDBoot + By default, the version of BCDBOOT.EXE that is present in \Windows\System32 + is used by Convert-WindowsImage. If you need to specify an alternate version, + use this parameter to do so. + + .PARAMETER MergeFolder + Specifies additional MergeFolder path to be added to the root of the VHD(X) + + .PARAMETER BCDinVHD + Specifies the purpose of the VHD(x). Use NativeBoot to skip cration of BCD store + inside the VHD(x). Use VirtualMachine (or do not specify this option) to ensure + the BCD store is created inside the VHD(x). + + .PARAMETER Driver + Full path to driver(s) (.inf files) to inject to the OS inside the VHD(x). + + .PARAMETER ExpandOnNativeBoot + Specifies whether to expand the VHD(x) to its maximum suze upon native boot. + The default is True. Set to False to disable expansion. + + .PARAMETER RDP + Enable Remote Desktop to connect to the OS inside the VHD(x) upon provisioning. + + .PARAMETER Parsec + Install Remote Desktop app Parsec. + + .PARAMETER ParsecVDD + Install Remote Desktop app Parsec Virtual Display Driver + + .PARAMETER DisableHVDD + Disable Hyper-V Display Driver + + .PARAMETER Numlock + Enable / Disable NumLock at logon + + .PARAMETER Feature + Enables specified Windows Feature(s). Note that you need to specify the Internal names + understood by DISM and DISM CMDLets (e.g. NetFx3) instead of the "Friendly" names + from Server Manager CMDLets (e.g. NET-Framework-Core). + + .PARAMETER Package + Injects specified Windows Package(s). Accepts path to either a directory or individual + CAB or MSU file. + + .PARAMETER ShowUI + Specifies that the Graphical User Interface should be displayed. + + .PARAMETER EnableDebugger + Configures kernel debugging for the VHD(X) being created. + EnableDebugger takes a single argument which specifies the debugging transport to use. + Valid transports are: None, Serial, 1394, USB, Network, Local. + Depending on the type of transport selected, additional configuration parameters will become + available. + + Serial: -ComPort - The COM port number to use while communicating with the debugger. + The default value is 1 (indicating COM1). + -BaudRate - The baud rate (in bps) to use while communicating with the debugger. + The default value is 115200, valid values are: + 9600, 19200, 38400, 56700, 115200 + + 1394: -Channel - The 1394 channel used to communicate with the debugger. + The default value is 10. + + USB: -Target - The target name used for USB debugging (the default value is "debugging"). + + Network: -IPAddress - The IP address of the debugging host computer. + -Port - The port on which to connect to the debugging host. + The default value is 50000, with a minimum value of 49152. + -Key - The key used to encrypt the connection. Only [0-9] and [a-z] are allowed. + -nodhcp - Prevents the use of DHCP to obtain the target IP address. + -newkey - Specifies that a new encryption key should be generated for the connection. + + .PARAMETER DismPath + Full Path to an alternative version of the Dism.exe tool. The default is the current OS version. + + .PARAMETER ApplyEA + Specifies that any EAs captured in the WIM should be applied to the VHD. + The default is False. + + .EXAMPLE + .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -WorkingDirectory D:\foo + This command will create a 40GB dynamically expanding VHD in the D:\foo folder. + The VHD will be based on the Professional edition from D:\foo\install.wim, + and will be named automatically. + + .EXAMPLE + .\Convert-WindowsImage.ps1 -SourcePath D:\foo\Win7SP1.iso -Edition Ultimate -VHDPath D:\foo\Win7_Ultimate_SP1.vhd + This command will parse the ISO file D:\foo\Win7SP1.iso and try to locate + \sources\install.wim. If that file is found, it will be used to create a + dynamically-expanding 40GB VHD containing the Ultimate SKU, and will be + named D:\foo\Win7_Ultimate_SP1.vhd + + .EXAMPLE + .\Convert-WindowsImage.ps1 -SourcePath D:\foo\install.wim -Edition Professional -EnableDebugger Serial -ComPort 2 -BaudRate 38400 + This command will create a VHD from D:\foo\install.wim of the Professional SKU. + Serial debugging will be enabled in the VHD via COM2 at a baud rate of 38400bps. + + .OUTPUTS + System.IO.FileInfo + #> + [CmdletBinding(DefaultParameterSetName = "SRC", + HelpURI = "https://github.com/Microsoft/Virtualization-Documentation/tree/master/hyperv-tools/Convert-WindowsImage")] + + param( + [Parameter(ParameterSetName = "SRC", Mandatory = $true,ValueFromPipeline = $true)] + [Alias("WIM")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateScript({ Test-Path $(Resolve-Path $_) })] + $SourcePath, + + [Parameter(ParameterSetName = "SRC")] + [Alias("DriveLetter")] + [string] + [ValidateNotNullOrEmpty()] + [string]$ISODriveLetter, + + [Parameter(ParameterSetName = "SRC")] + [Alias("GPU")] + [string] + [ValidateNotNullOrEmpty()] + [string]$GPUName, + + [Parameter(ParameterSetName = "SRC")] + [Alias("TeamID")] + [string] + #[ValidateNotNullOrEmpty()] + [string]$Team_ID, + + [Parameter(ParameterSetName = "SRC")] + [Alias("Teamkey")] + [string] + #[ValidateNotNullOrEmpty()] + [string]$Key, + + [Parameter(ParameterSetName = "SRC")] + [switch] + $CacheSource = $false, + + [Parameter(ParameterSetName = "SRC")] + [Alias("SKU")] + [string[]] + [ValidateNotNullOrEmpty()] + $Edition, + + [Parameter(ParameterSetName = "SRC")] + [Alias("WorkDir")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateScript({ Test-Path $_ })] + $WorkingDirectory = $pwd, + + [Parameter(ParameterSetName = "SRC")] + [Alias("TempDir")] + [string] + [ValidateNotNullOrEmpty()] + $TempDirectory = $env:Temp, + + [Parameter(ParameterSetName = "SRC")] + [Alias("VHD")] + [string] + [ValidateNotNullOrEmpty()] + $VHDPath, + + [Parameter(ParameterSetName = "SRC")] + [Alias("Size")] + [uint64] + [ValidateNotNullOrEmpty()] + [ValidateRange(512MB,64TB)] + $SizeBytes = 25GB, + + [Parameter(ParameterSetName = "SRC")] + [Alias("Format")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateSet("VHD","VHDX","AUTO")] + $VHDFormat = "AUTO", + + [Parameter(ParameterSetName = "SRC")] + [Alias("MergeFolder")] + [string] + [ValidateNotNullOrEmpty()] + $MergeFolderPath = "", + + [Parameter(ParameterSetName = "SRC",Mandatory = $true)] + [Alias("Layout")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateSet("BIOS","UEFI","WindowsToGo")] + $DiskLayout, + + [Parameter(ParameterSetName = "SRC")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateSet("NativeBoot","VirtualMachine")] + $BCDinVHD = "VirtualMachine", + + [Parameter(ParameterSetName = "SRC")] + [Parameter(ParameterSetName = "UI")] + [string] + $BCDBoot = "bcdboot.exe", + + [Parameter(ParameterSetName = "SRC")] + [Parameter(ParameterSetName = "UI")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateSet("None","Serial","1394","USB","Local","Network")] + $EnableDebugger = "None", + + [Parameter(ParameterSetName = "SRC")] + [string[]] + [ValidateNotNullOrEmpty()] + $Feature, + + [Parameter(ParameterSetName = "SRC")] + [string[]] + [ValidateNotNullOrEmpty()] + [ValidateScript({ Test-Path $(Resolve-Path $_) })] + $Driver, + + [Parameter(ParameterSetName = "SRC")] + [string[]] + [ValidateNotNullOrEmpty()] + [ValidateScript({ Test-Path $(Resolve-Path $_) })] + $Package, + + [Parameter(ParameterSetName = "SRC")] + [switch] + $ExpandOnNativeBoot = $true, + + [Parameter(ParameterSetName = "SRC")] + [bool] + $RDP, + + [Parameter(ParameterSetName = "SRC")] + [bool] + $Parsec, + + [Parameter(ParameterSetName = "SRC")] + [bool] + $ParsecVDD, + + [Parameter(ParameterSetName = "SRC")] + [bool] + $DisableHVDD, + + [Parameter(ParameterSetName = "SRC")] + [bool] + $NumLock, + + [Parameter(ParameterSetName = "SRC")] + [Alias("Unattend")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateScript({ Test-Path $(Resolve-Path $_) })] + $UnattendPath, + + [Parameter(ParameterSetName = "SRC")] + [Parameter(ParameterSetName = "UI")] + [switch] + $Passthru, + + [Parameter(ParameterSetName = "SRC")] + [string] + [ValidateNotNullOrEmpty()] + [ValidateScript({ Test-Path $(Resolve-Path $_) })] + $DismPath, + + [Parameter(ParameterSetName = "SRC")] + [switch] + $ApplyEA = $false, + + [Parameter(ParameterSetName = "UI")] + [switch] + $ShowUI + ) + #region Code + + # Begin Dynamic Parameters + # Create the parameters for the various types of debugging. + dynamicparam { + #Set-StrictMode -version 3 + # Set up the dynamic parameters. + # Dynamic parameters are only available if certain conditions are met, so they'll only show up + # as valid parameters when those conditions apply. Here, the conditions are based on the value of + # the EnableDebugger parameter. Depending on which of a set of values is the specified argument + # for EnableDebugger, different parameters will light up, as outlined below. + + $parameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary + + if (!(Test-Path Variable:Private:EnableDebugger)) { + return $parameterDictionary + } + + switch ($EnableDebugger){ + "Serial" { + #region ComPort + + $ComPortAttr = New-Object System.Management.Automation.ParameterAttribute + $ComPortAttr.ParameterSetName = "__AllParameterSets" + $ComPortAttr.Mandatory = $false + $ComPortValidator = New-Object System.Management.Automation.ValidateRangeAttribute ( + 1, + 10 # Is that a good maximum? + ) + $ComPortNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $ComPortAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $ComPortAttrCollection.Add($ComPortAttr) + $ComPortAttrCollection.Add($ComPortValidator) + $ComPortAttrCollection.Add($ComPortNotNull) + $ComPort = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "ComPort", + [uint16], + $ComPortAttrCollection + ) + # By default, use COM1 + $ComPort.Value = 1 + $parameterDictionary.Add("ComPort",$ComPort) + #endregion ComPort + + #region BaudRate + $BaudRateAttr = New-Object System.Management.Automation.ParameterAttribute + $BaudRateAttr.ParameterSetName = "__AllParameterSets" + $BaudRateAttr.Mandatory = $false + $BaudRateValidator = New-Object System.Management.Automation.ValidateSetAttribute ( + 9600,19200,38400,57600,115200 + ) + $BaudRateNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $BaudRateAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $BaudRateAttrCollection.Add($BaudRateAttr) + $BaudRateAttrCollection.Add($BaudRateValidator) + $BaudRateAttrCollection.Add($BaudRateNotNull) + $BaudRate = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "BaudRate", + [uint32], + $BaudRateAttrCollection + ) + # By default, use 115,200. + $BaudRate.Value = 115200 + $parameterDictionary.Add("BaudRate",$BaudRate) + #endregion BaudRate + + break + } + + "1394" { + $ChannelAttr = New-Object System.Management.Automation.ParameterAttribute + $ChannelAttr.ParameterSetName = "__AllParameterSets" + $ChannelAttr.Mandatory = $false + $ChannelValidator = New-Object System.Management.Automation.ValidateRangeAttribute ( + 0, + 62 + ) + $ChannelNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $ChannelAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $ChannelAttrCollection.Add($ChannelAttr) + $ChannelAttrCollection.Add($ChannelValidator) + $ChannelAttrCollection.Add($ChannelNotNull) + $Channel = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "Channel", + [uint16], + $ChannelAttrCollection + ) + # By default, use channel 10 + $Channel.Value = 10 + $parameterDictionary.Add("Channel",$Channel) + break + } + + "USB" { + $TargetAttr = New-Object System.Management.Automation.ParameterAttribute + $TargetAttr.ParameterSetName = "__AllParameterSets" + $TargetAttr.Mandatory = $false + $TargetNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $TargetAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $TargetAttrCollection.Add($TargetAttr) + $TargetAttrCollection.Add($TargetNotNull) + $Target = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "Target", + [string], + $TargetAttrCollection + ) + # By default, use target = "debugging" + $Target.Value = "Debugging" + $parameterDictionary.Add("Target",$Target) + break + } + + "Network" { + #region IP + $IpAttr = New-Object System.Management.Automation.ParameterAttribute + $IpAttr.ParameterSetName = "__AllParameterSets" + $IpAttr.Mandatory = $true + $IpValidator = New-Object System.Management.Automation.ValidatePatternAttribute ( + "\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" + ) + $IpNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $IpAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $IpAttrCollection.Add($IpAttr) + $IpAttrCollection.Add($IpValidator) + $IpAttrCollection.Add($IpNotNull) + $IP = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "IPAddress", + [string], + $IpAttrCollection + ) + # There's no good way to set a default value for this. + $parameterDictionary.Add("IPAddress",$IP) + #endregion IP + + #region Port + $PortAttr = New-Object System.Management.Automation.ParameterAttribute + $PortAttr.ParameterSetName = "__AllParameterSets" + $PortAttr.Mandatory = $false + $PortValidator = New-Object System.Management.Automation.ValidateRangeAttribute ( + 49152, + 50039 + ) + $PortNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $PortAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $PortAttrCollection.Add($PortAttr) + $PortAttrCollection.Add($PortValidator) + $PortAttrCollection.Add($PortNotNull) + $Port = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "Port", + [uint16], + $PortAttrCollection + ) + # By default, use port 50000 + $Port.Value = 50000 + $parameterDictionary.Add("Port",$Port) + #endregion Port + + #region Key + $KeyAttr = New-Object System.Management.Automation.ParameterAttribute + $KeyAttr.ParameterSetName = "__AllParameterSets" + $KeyAttr.Mandatory = $true + $KeyValidator = New-Object System.Management.Automation.ValidatePatternAttribute ( + "\b([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+).([A-Z0-9]+)\b" + ) + $KeyNotNull = New-Object System.Management.Automation.ValidateNotNullOrEmptyAttribute + $KeyAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $KeyAttrCollection.Add($KeyAttr) + $KeyAttrCollection.Add($KeyValidator) + $KeyAttrCollection.Add($KeyNotNull) + $Key = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "Key", + [string], + $KeyAttrCollection + ) + # Don't set a default key. + $parameterDictionary.Add("Key",$Key) + #endregion Key + + #region NoDHCP + $NoDHCPAttr = New-Object System.Management.Automation.ParameterAttribute + $NoDHCPAttr.ParameterSetName = "__AllParameterSets" + $NoDHCPAttr.Mandatory = $false + $NoDHCPAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $NoDHCPAttrCollection.Add($NoDHCPAttr) + $NoDHCP = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "NoDHCP", + [switch], + $NoDHCPAttrCollection + ) + $parameterDictionary.Add("NoDHCP",$NoDHCP) + #endregion NoDHCP + + #region NewKey + $NewKeyAttr = New-Object System.Management.Automation.ParameterAttribute + $NewKeyAttr.ParameterSetName = "__AllParameterSets" + $NewKeyAttr.Mandatory = $false + $NewKeyAttrCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] + $NewKeyAttrCollection.Add($NewKeyAttr) + $NewKey = New-Object System.Management.Automation.RuntimeDefinedParameter ( + "NewKey", + [switch], + $NewKeyAttrCollection + ) + # Don't set a default key. + $parameterDictionary.Add("NewKey",$NewKey) + #endregion NewKey + break + } + # There's nothing to do for local debugging. + # Synthetic debugging is not yet implemented. + default { + break + } + } + + return $parameterDictionary + } + + begin { + $PARTITION_STYLE_MBR = 0x00000000 # The default value + $PARTITION_STYLE_GPT = 0x00000001 # Just in case... + # Version information that can be populated by timebuild. + $ScriptVersion = data { + ConvertFrom-StringData -StringData @" + Major = 10 + Minor = 0 + Build = 14278 + Qfe = 1000 + Branch = rs1_es_media + Timestamp = 160201-1707 + Flavor = amd64fre +"@ + } + $myVersion = "$($ScriptVersion.Major).$($ScriptVersion.Minor).$($ScriptVersion.Build).$($ScriptVersion.QFE).$($ScriptVersion.Flavor).$($ScriptVersion.Branch).$($ScriptVersion.Timestamp)" + $scriptName = "Convert-WindowsImage" # Name of the script, obviously. + $sessionKey = [guid]::NewGuid().ToString() # Session key, used for keeping records unique between multiple runs. + $logFolder = "$($TempDirectory)\$($scriptName)\$($sessionKey)" # Log folder path. + $vhdMaxSize = 2040GB # Maximum size for VHD is ~2040GB. + $vhdxMaxSize = 64TB # Maximum size for VHDX is ~64TB. + $lowestSupportedVersion = New-Object Version "6.1" # The lowest supported *image* version; making sure we don't run against Vista/2k8. + $lowestSupportedBuild = 9200 # The lowest supported *host* build. Set to Win8 CP. + $transcripting = $false + # Since we use the VHDFormat in output, make it uppercase. + # We'll make it lowercase again when we use it as a file extension. + $VHDFormat = $VHDFormat.ToUpper() + # Banner text displayed during each run. + $header = @" +Windows(R) Image to Virtual Hard Disk Converter for Windows(R) 10 +Copyright (C) Microsoft Corporation. All rights reserved. +Version $myVersion + +"@ + # Text used as the banner in the UI. + $uiHeader = @" +You can use the fields below to configure the VHD or VHDX that you want to create! +"@ + #region Helper Functions + <# + Functions to mount and dismount registry hives. + These hives will automatically be accessible via the HKLM:\ registry PSDrive. + + It should be noted that I have more confidence in using the RegLoadKey and + RegUnloadKey Win32 APIs than I do using REG.EXE - it just seems like we should + do things ourselves if we can, instead of using yet another binary. + + Consider this a TODO for future versions. + #> + function Mount-RegistryHive { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true,ValueFromPipeline = $true,Position = 0)] + [System.IO.FileInfo] + [ValidateNotNullOrEmpty()] + [ValidateScript({ $_.Exists })] + $Hive + ) + $mountKey = [System.Guid]::NewGuid().ToString() + $regPath = "REG.EXE" + if (Test-Path HKLM:\$mountKey) { + throw "The registry path already exists. I should just regenerate it, but I'm lazy." + } + $regArgs = ( + "LOAD", + "HKLM\$mountKey", + $Hive.FullName + ) + try { + Run-Executable -Executable $regPath -Arguments $regArgs + } catch { + throw + } + # Set a global variable containing the name of the mounted registry key + # so we can unmount it if there's an error. + $global:mountedHive = $mountKey + return $mountKey + } + + function Dismount-RegistryHive { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true,ValueFromPipeline = $true,Position = 0)] + [string] + [ValidateNotNullOrEmpty()] + $HiveMountPoint + ) + + $regPath = "REG.EXE" + + $regArgs = ( + "UNLOAD", + "HKLM\$($HiveMountPoint)" + ) + + Run-Executable -Executable $regPath -Arguments $regArgs + + $global:mountedHive = $null + } + + function Test-Admin { + <# + .SYNOPSIS + Short function to determine whether the logged-on user is an administrator. + + .EXAMPLE + Do you honestly need one? There are no parameters! + + .OUTPUTS + $true if user is admin. + $false if user is not an admin. + #> + [CmdletBinding()] + param() + $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent()) + $isAdmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) + Write-W2VTrace "isUserAdmin? $isAdmin" + return $isAdmin + } + + function Get-WindowsBuildNumber { + $os = Get-WmiObject -Class Win32_OperatingSystem + return [int]($os.BuildNumber) + } + + function Test-WindowsVersion { + $isWin8 = ((Get-WindowsBuildNumber) -ge [int]$lowestSupportedBuild) + Write-W2VTrace "is Windows 8 or Higher? $isWin8" + return $isWin8 + } + + function Write-W2VTrace { + # Function to make the Write-Verbose output... well... exactly the same as it was before. + [CmdletBinding()] + param( + [Parameter(Mandatory = $true,ValueFromPipeline = $true)] + [string] + [ValidateNotNullOrEmpty()] + $text + ) + Write-Verbose $text + } + + function Write-W2VError { + # Function to make the Write-Host (NOT Write-Error) output prettier in the case of an error. + [CmdletBinding()] + param( + [Parameter(Mandatory = $true,ValueFromPipeline = $true)] + [string] + [ValidateNotNullOrEmpty()] + $text + ) + Write-Host "ERROR : $($text)" + } + + function Write-W2VWarn { + # Function to make the Write-Host (NOT Write-Warning) output prettier. + [CmdletBinding()] + param( + [Parameter(Mandatory = $true,ValueFromPipeline = $true)] + [string] + [ValidateNotNullOrEmpty()] + $text + ) + Write-Host "WARN : $($text)" -ForegroundColor (Get-Host).PrivateData.WarningForegroundColor + } + + function Run-Executable { + <# + .SYNOPSIS + Runs an external executable file, and validates the error level. + + .PARAMETER Executable + The path to the executable to run and monitor. + + .PARAMETER Arguments + An array of arguments to pass to the executable when it's executed. + + .PARAMETER SuccessfulErrorCode + The error code that means the executable ran successfully. + The default value is 0. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] + [ValidateNotNullOrEmpty()] + $Executable, + [Parameter(Mandatory = $true)] + [string[]] + [ValidateNotNullOrEmpty()] + $Arguments, + [Parameter()] + [int] + [ValidateNotNullOrEmpty()] + $SuccessfulErrorCode = 0 + ) + Write-W2VTrace "Running $Executable $Arguments" + $ret = Start-Process ` + -FilePath $Executable ` + -ArgumentList $Arguments ` + -NoNewWindow ` + -Wait ` + -RedirectStandardOutput "$($TempDirectory)\$($scriptName)\$($sessionKey)\$($Executable)-StandardOutput.txt" ` + -RedirectStandardError "$($TempDirectory)\$($scriptName)\$($sessionKey)\$($Executable)-StandardError.txt" ` + -Passthru + + Write-W2VTrace "Return code was $($ret.ExitCode)." + if ($ret.ExitCode -ne $SuccessfulErrorCode) { + throw "$Executable failed with code $($ret.ExitCode)!" + } + } + + function Test-IsNetworkLocation { + <# + .SYNOPSIS + Determines whether or not a given path is a network location or a local drive. + + .DESCRIPTION + Function to determine whether or not a specified path is a local path, a UNC path, + or a mapped network drive. + + .PARAMETER Path + #> + [CmdletBinding()] + param( + [Parameter(ValueFromPipeline = $true)] + [string] + [ValidateNotNullOrEmpty()] + $Path + ) + + $result = $false + if ([bool]([uri]$Path).IsUNC) { + $result = $true + } else { + $driveInfo = [IO.DriveInfo]((Resolve-Path $Path).Path) + if ($driveInfo.DriveType -eq "Network") { + $result = $true + } + } + + return $result + } + #endregion Helper Functions + } + + process { + Write-Host $header + $disk = $null + $openWim = $null + $openIso = $null + $openImage = $null + $vhdFinalName = $null + $vhdFinalPath = $null + $mountedHive = $null + $isoPath = $null + $tempSource = $null + + if (Get-Command Get-WindowsOptionalFeature -ErrorAction SilentlyContinue) { + try { + $hyperVEnabled = $((Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V).State -eq "Enabled") + } catch { + # WinPE DISM does not support online queries. This will throw on non-WinPE machines + $winpeVersion = (Get-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\WinPE').Version + + Write-W2VInfo "Running WinPE version $winpeVersion" + + $hyperVEnabled = $false + } + } else { + $hyperVEnabled = $false + } + + $vhd = @() + + try { + # Create log folder + if (Test-Path $logFolder) { + $null = Remove-Item $logFolder -Force -Recurse + } + $null = mkdir $logFolder -Force + # Try to start transcripting. If it's already running, we'll get an exception and swallow it. + try { + $null = Start-Transcript -Path (Join-Path $logFolder "Convert-WindowsImageTranscript.txt") -Force -ErrorAction SilentlyContinue + $transcripting = $true + } catch { + Write-W2VWarn "Transcription is already running. No Convert-WindowsImage-specific transcript will be created." + $transcripting = $false + } + # + # Add types + # + Add-WindowsImageTypes + # Check to make sure we're running as Admin. + if (!(Test-Admin)) { + throw "Images can only be applied by an administrator. Please launch PowerShell elevated and run this script again." + } + # Check to make sure we're running on Win8. + if (!(Test-WindowsVersion)) { + 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." + } + # Resolve the path for the unattend file. + if (![string]::IsNullOrEmpty($UnattendPath)) { + $UnattendPath = (Resolve-Path $UnattendPath).Path + } + if ($ShowUI) { + Write-W2VInfo "Launching UI..." + Add-Type -AssemblyName System.Drawing,System.Windows.Forms + #region Form Objects + $frmMain = New-Object System.Windows.Forms.Form + $groupBox4 = New-Object System.Windows.Forms.GroupBox + $btnGo = New-Object System.Windows.Forms.Button + $groupBox3 = New-Object System.Windows.Forms.GroupBox + $txtVhdName = New-Object System.Windows.Forms.TextBox + $label6 = New-Object System.Windows.Forms.Label + $btnWrkBrowse = New-Object System.Windows.Forms.Button + $cmbVhdSizeUnit = New-Object System.Windows.Forms.ComboBox + $numVhdSize = New-Object System.Windows.Forms.NumericUpDown + $cmbVhdFormat = New-Object System.Windows.Forms.ComboBox + $label5 = New-Object System.Windows.Forms.Label + $txtWorkingDirectory = New-Object System.Windows.Forms.TextBox + $label4 = New-Object System.Windows.Forms.Label + $label3 = New-Object System.Windows.Forms.Label + $label2 = New-Object System.Windows.Forms.Label + $label7 = New-Object System.Windows.Forms.Label + $txtUnattendFile = New-Object System.Windows.Forms.TextBox + $btnUnattendBrowse = New-Object System.Windows.Forms.Button + $groupBox2 = New-Object System.Windows.Forms.GroupBox + $cmbSkuList = New-Object System.Windows.Forms.ComboBox + $label1 = New-Object System.Windows.Forms.Label + $groupBox1 = New-Object System.Windows.Forms.GroupBox + $txtSourcePath = New-Object System.Windows.Forms.TextBox + $btnBrowseWim = New-Object System.Windows.Forms.Button + $openFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog + $openFolderDialog1 = New-Object System.Windows.Forms.FolderBrowserDialog + $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState + #endregion Form Objects + + #region Event scriptblocks. + $btnGo_OnClick = { + $frmMain.Close() + } + $btnWrkBrowse_OnClick = { + $openFolderDialog1.RootFolder = "Desktop" + $openFolderDialog1.Description = "Select the folder you'd like your VHD(X) to be created in." + $openFolderDialog1.SelectedPath = $WorkingDirectory + $ret = $openFolderDialog1.ShowDialog() + if ($ret -ilike "ok") { + $WorkingDirectory = $txtWorkingDirectory = $openFolderDialog1.SelectedPath + Write-W2VInfo "Selected Working Directory is $WorkingDirectory..." + } + } + $btnUnattendBrowse_OnClick = { + $openFileDialog1.InitialDirectory = $pwd + $openFileDialog1.Filter = "XML files (*.xml)|*.XML|All files (*.*)|*.*" + $openFileDialog1.FilterIndex = 1 + $openFileDialog1.CheckFileExists = $true + $openFileDialog1.CheckPathExists = $true + $openFileDialog1.FileName = $null + $openFileDialog1.ShowHelp = $false + $openFileDialog1.Title = "Select an unattend file..." + $ret = $openFileDialog1.ShowDialog() + if ($ret -ilike "ok") { + $UnattendPath = $txtUnattendFile.Text = $openFileDialog1.FileName + } + } + $btnBrowseWim_OnClick = { + $openFileDialog1.InitialDirectory = $pwd + $openFileDialog1.Filter = "All compatible files (*.ISO, *.WIM)|*.ISO;*.WIM|All files (*.*)|*.*" + $openFileDialog1.FilterIndex = 1 + $openFileDialog1.CheckFileExists = $true + $openFileDialog1.CheckPathExists = $true + $openFileDialog1.FileName = $null + $openFileDialog1.ShowHelp = $false + $openFileDialog1.Title = "Select a source file..." + $ret = $openFileDialog1.ShowDialog() + if ($ret -ilike "ok") { + if (([IO.FileInfo]$openFileDialog1.FileName).Extension -ilike ".iso") { + if (Test-IsNetworkLocation $openFileDialog1.FileName) { + Write-W2VInfo "Copying ISO $(Split-Path $openFileDialog1.FileName -Leaf) to temp folder..." + Write-W2VWarn "The UI may become non-responsive while this copy takes place..." + Copy-Item -Path $openFileDialog1.FileName -Destination $TempDirectory -Force + $openFileDialog1.FileName = "$($TempDirectory)\$(Split-Path $openFileDialog1.FileName -Leaf)" + } + $txtSourcePath.Text = $isoPath = (Resolve-Path $openFileDialog1.FileName).Path + Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..." + $script:SourcePath = "$($driveLetter):\sources\install.wim" + # Check to see if there's a WIM file we can muck about with. + Write-W2VInfo "Looking for $($SourcePath)..." + if (!(Test-Path $SourcePath)) { + throw "The specified ISO does not appear to be valid Windows installation media." + } + } else { + $txtSourcePath.Text = $script:SourcePath = $openFileDialog1.FileName + } + # Check to see if the WIM is local, or on a network location. If the latter, copy it locally. + if (Test-IsNetworkLocation $SourcePath){ + Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..." + Write-W2VWarn "The UI may become non-responsive while this copy takes place..." + Copy-Item -Path $SourcePath -Destination $TempDirectory -Force + $txtSourcePath.Text = $script:SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)" + } + $script:SourcePath = (Resolve-Path $SourcePath).Path + Write-W2VInfo "Scanning WIM metadata..." + $tempOpenWim = $null + try { + $tempOpenWim = New-Object WIM2VHD.WimFile $SourcePath + # Let's see if we're running against an unstaged build. If we are, we need to blow up. + if ($tempOpenWim.ImageNames.Contains("Windows Longhorn Client") -or + $tempOpenWim.ImageNames.Contains("Windows Longhorn Server") -or + $tempOpenWim.ImageNames.Contains("Windows Longhorn Server Core")){ + [Windows.Forms.MessageBox]::Show( + "Convert-WindowsImage cannot run against unstaged builds. Please try again with a staged build.", + "WIM is incompatible!", + "OK", + "Error" + ) + return + } else { + $tempOpenWim.Images | ForEach-Object { $cmbSkuList.Items.Add($_.ImageFlags) } + $cmbSkuList.SelectedIndex = 0 + } + + } catch { + throw "Unable to load WIM metadata!" + } finally { + $tempOpenWim.Close() + Write-W2VTrace "Closing WIM metadata..." + } + } + } + $OnLoadForm_StateCorrection = { + # Correct the initial state of the form to prevent the .Net maximized form issue + $frmMain.WindowState = $InitialFormWindowState + } + #endregion Event scriptblocks + + # Figure out VHD size and size unit. + $unit = $null + switch ([math]::Round($SizeBytes.ToString().Length / 3)) { + 3 { $unit = "MB"; break } + 4 { $unit = "GB"; break } + 5 { $unit = "TB"; break } + default { $unit = ""; break } + } + $quantity = Invoke-Expression -Command "$($SizeBytes) / 1$($unit)" + + #region Form Code + #region frmMain + $frmMain.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 579 + $System_Drawing_Size.Width = 512 + $frmMain.ClientSize = $System_Drawing_Size + $frmMain.Font = New-Object System.Drawing.Font ("Segoe UI",10,0,3,1) + $frmMain.FormBorderStyle = 1 + $frmMain.MaximizeBox = $false + $frmMain.MinimizeBox = $false + $frmMain.Name = "frmMain" + $frmMain.StartPosition = 1 + $frmMain.Text = "Convert-WindowsImage UI" + #endregion frmMain + + #region groupBox4 + $groupBox4.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 10 + $System_Drawing_Point.Y = 498 + $groupBox4.Location = $System_Drawing_Point + $groupBox4.Name = "groupBox4" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 69 + $System_Drawing_Size.Width = 489 + $groupBox4.Size = $System_Drawing_Size + $groupBox4.TabIndex = 8 + $groupBox4.TabStop = $false + $groupBox4.Text = "4. Make the VHD!" + $frmMain.Controls.Add($groupBox4) + #endregion groupBox4 + + #region btnGo + $btnGo.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 39 + $System_Drawing_Point.Y = 24 + $btnGo.Location = $System_Drawing_Point + $btnGo.Name = "btnGo" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 33 + $System_Drawing_Size.Width = 415 + $btnGo.Size = $System_Drawing_Size + $btnGo.TabIndex = 0 + $btnGo.Text = "&Make my VHD" + $btnGo.UseVisualStyleBackColor = $true + $btnGo.DialogResult = "OK" + $btnGo.add_Click($btnGo_OnClick) + $groupBox4.Controls.Add($btnGo) + $frmMain.AcceptButton = $btnGo + #endregion btnGo + + #region groupBox3 + $groupBox3.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 10 + $System_Drawing_Point.Y = 243 + $groupBox3.Location = $System_Drawing_Point + $groupBox3.Name = "groupBox3" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 245 + $System_Drawing_Size.Width = 489 + $groupBox3.Size = $System_Drawing_Size + $groupBox3.TabIndex = 7 + $groupBox3.TabStop = $false + $groupBox3.Text = "3. Choose configuration options" + $frmMain.Controls.Add($groupBox3) + #endregion groupBox3 + + #region txtVhdName + $txtVhdName.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 150 + $txtVhdName.Location = $System_Drawing_Point + $txtVhdName.Name = "txtVhdName" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 418 + $txtVhdName.Size = $System_Drawing_Size + $txtVhdName.TabIndex = 10 + $groupBox3.Controls.Add($txtVhdName) + #endregion txtVhdName + + #region txtUnattendFile + $txtUnattendFile.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 198 + $txtUnattendFile.Location = $System_Drawing_Point + $txtUnattendFile.Name = "txtUnattendFile" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 418 + $txtUnattendFile.Size = $System_Drawing_Size + $txtUnattendFile.TabIndex = 11 + $groupBox3.Controls.Add($txtUnattendFile) + #endregion txtUnattendFile + + #region label7 + $label7.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 23 + $System_Drawing_Point.Y = 180 + $label7.Location = $System_Drawing_Point + $label7.Name = "label7" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 23 + $System_Drawing_Size.Width = 175 + $label7.Size = $System_Drawing_Size + $label7.Text = "Unattend File (Optional)" + $groupBox3.Controls.Add($label7) + #endregion label7 + + #region label6 + $label6.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 23 + $System_Drawing_Point.Y = 132 + $label6.Location = $System_Drawing_Point + $label6.Name = "label6" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 23 + $System_Drawing_Size.Width = 175 + $label6.Size = $System_Drawing_Size + $label6.Text = "VHD Name (Optional)" + $groupBox3.Controls.Add($label6) + #endregion label6 + + #region btnUnattendBrowse + $btnUnattendBrowse.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 449 + $System_Drawing_Point.Y = 199 + $btnUnattendBrowse.Location = $System_Drawing_Point + $btnUnattendBrowse.Name = "btnUnattendBrowse" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 27 + $btnUnattendBrowse.Size = $System_Drawing_Size + $btnUnattendBrowse.TabIndex = 9 + $btnUnattendBrowse.Text = "..." + $btnUnattendBrowse.UseVisualStyleBackColor = $true + $btnUnattendBrowse.add_Click($btnUnattendBrowse_OnClick) + $groupBox3.Controls.Add($btnUnattendBrowse) + #endregion btnUnattendBrowse + + #region btnWrkBrowse + $btnWrkBrowse.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 449 + $System_Drawing_Point.Y = 98 + $btnWrkBrowse.Location = $System_Drawing_Point + $btnWrkBrowse.Name = "btnWrkBrowse" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 27 + $btnWrkBrowse.Size = $System_Drawing_Size + $btnWrkBrowse.TabIndex = 9 + $btnWrkBrowse.Text = "..." + $btnWrkBrowse.UseVisualStyleBackColor = $true + $btnWrkBrowse.add_Click($btnWrkBrowse_OnClick) + $groupBox3.Controls.Add($btnWrkBrowse) + #endregion btnWrkBrowse + + #region cmbVhdSizeUnit + $cmbVhdSizeUnit.DataBindings.DefaultDataSourceUpdateMode = 0 + $cmbVhdSizeUnit.FormattingEnabled = $true + $cmbVhdSizeUnit.Items.Add("MB") | Out-Null + $cmbVhdSizeUnit.Items.Add("GB") | Out-Null + $cmbVhdSizeUnit.Items.Add("TB") | Out-Null + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 409 + $System_Drawing_Point.Y = 42 + $cmbVhdSizeUnit.Location = $System_Drawing_Point + $cmbVhdSizeUnit.Name = "cmbVhdSizeUnit" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 67 + $cmbVhdSizeUnit.Size = $System_Drawing_Size + $cmbVhdSizeUnit.TabIndex = 5 + $cmbVhdSizeUnit.Text = $unit + $groupBox3.Controls.Add($cmbVhdSizeUnit) + #endregion cmbVhdSizeUnit + + #region numVhdSize + $numVhdSize.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 340 + $System_Drawing_Point.Y = 42 + $numVhdSize.Location = $System_Drawing_Point + $numVhdSize.Name = "numVhdSize" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 63 + $numVhdSize.Size = $System_Drawing_Size + $numVhdSize.TabIndex = 4 + $numVhdSize.Value = $quantity + $groupBox3.Controls.Add($numVhdSize) + #endregion numVhdSize + + #region cmbVhdFormat + $cmbVhdFormat.DataBindings.DefaultDataSourceUpdateMode = 0 + $cmbVhdFormat.FormattingEnabled = $true + $cmbVhdFormat.Items.Add("VHD") | Out-Null + $cmbVhdFormat.Items.Add("VHDX") | Out-Null + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 42 + $cmbVhdFormat.Location = $System_Drawing_Point + $cmbVhdFormat.Name = "cmbVhdFormat" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 136 + $cmbVhdFormat.Size = $System_Drawing_Size + $cmbVhdFormat.TabIndex = 0 + $cmbVhdFormat.Text = $VHDFormat + $groupBox3.Controls.Add($cmbVhdFormat) + #endregion cmbVhdFormat + + #region label5 + $label5.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 23 + $System_Drawing_Point.Y = 76 + $label5.Location = $System_Drawing_Point + $label5.Name = "label5" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 23 + $System_Drawing_Size.Width = 264 + $label5.Size = $System_Drawing_Size + $label5.TabIndex = 8 + $label5.Text = "Working Directory" + $groupBox3.Controls.Add($label5) + #endregion label5 + + #region txtWorkingDirectory + $txtWorkingDirectory.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 99 + $txtWorkingDirectory.Location = $System_Drawing_Point + $txtWorkingDirectory.Name = "txtWorkingDirectory" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 418 + $txtWorkingDirectory.Size = $System_Drawing_Size + $txtWorkingDirectory.TabIndex = 7 + $txtWorkingDirectory.Text = $WorkingDirectory + $groupBox3.Controls.Add($txtWorkingDirectory) + #endregion txtWorkingDirectory + + #region label4 + $label4.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 340 + $System_Drawing_Point.Y = 21 + $label4.Location = $System_Drawing_Point + $label4.Name = "label4" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 27 + $System_Drawing_Size.Width = 86 + $label4.Size = $System_Drawing_Size + $label4.TabIndex = 6 + $label4.Text = "VHD Size" + $groupBox3.Controls.Add($label4) + #endregion label4 + + #region label3 + $label3.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 176 + $System_Drawing_Point.Y = 21 + $label3.Location = $System_Drawing_Point + $label3.Name = "label3" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 27 + $System_Drawing_Size.Width = 92 + $label3.Size = $System_Drawing_Size + $label3.TabIndex = 3 + $label3.Text = "VHD Type" + $groupBox3.Controls.Add($label3) + #endregion label3 + + #region label2 + $label2.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 21 + $label2.Location = $System_Drawing_Point + $label2.Name = "label2" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 30 + $System_Drawing_Size.Width = 118 + $label2.Size = $System_Drawing_Size + $label2.TabIndex = 1 + $label2.Text = "VHD Format" + $groupBox3.Controls.Add($label2) + #endregion label2 + + #region groupBox2 + $groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 10 + $System_Drawing_Point.Y = 169 + $groupBox2.Location = $System_Drawing_Point + $groupBox2.Name = "groupBox2" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 68 + $System_Drawing_Size.Width = 490 + $groupBox2.Size = $System_Drawing_Size + $groupBox2.TabIndex = 6 + $groupBox2.TabStop = $false + $groupBox2.Text = "2. Choose a SKU from the list" + $frmMain.Controls.Add($groupBox2) + #endregion groupBox2 + + #region cmbSkuList + $cmbSkuList.DataBindings.DefaultDataSourceUpdateMode = 0 + $cmbSkuList.FormattingEnabled = $true + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 24 + $cmbSkuList.Location = $System_Drawing_Point + $cmbSkuList.Name = "cmbSkuList" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 452 + $cmbSkuList.Size = $System_Drawing_Size + $cmbSkuList.TabIndex = 2 + $groupBox2.Controls.Add($cmbSkuList) + #endregion cmbSkuList + + #region label1 + $label1.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 23 + $System_Drawing_Point.Y = 21 + $label1.Location = $System_Drawing_Point + $label1.Name = "label1" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 71 + $System_Drawing_Size.Width = 464 + $label1.Size = $System_Drawing_Size + $label1.TabIndex = 5 + $label1.Text = $uiHeader + $frmMain.Controls.Add($label1) + #endregion label1 + + #region groupBox1 + $groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 10 + $System_Drawing_Point.Y = 95 + $groupBox1.Location = $System_Drawing_Point + $groupBox1.Name = "groupBox1" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 68 + $System_Drawing_Size.Width = 490 + $groupBox1.Size = $System_Drawing_Size + $groupBox1.TabIndex = 4 + $groupBox1.TabStop = $false + $groupBox1.Text = "1. Choose a source" + $frmMain.Controls.Add($groupBox1) + #endregion groupBox1 + + #region txtSourcePath + $txtSourcePath.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 25 + $System_Drawing_Point.Y = 24 + $txtSourcePath.Location = $System_Drawing_Point + $txtSourcePath.Name = "txtSourcePath" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 418 + $txtSourcePath.Size = $System_Drawing_Size + $txtSourcePath.TabIndex = 0 + $groupBox1.Controls.Add($txtSourcePath) + #endregion txtSourcePath + + #region btnBrowseWim + $btnBrowseWim.DataBindings.DefaultDataSourceUpdateMode = 0 + $System_Drawing_Point = New-Object System.Drawing.Point + $System_Drawing_Point.X = 449 + $System_Drawing_Point.Y = 24 + $btnBrowseWim.Location = $System_Drawing_Point + $btnBrowseWim.Name = "btnBrowseWim" + $System_Drawing_Size = New-Object System.Drawing.Size + $System_Drawing_Size.Height = 25 + $System_Drawing_Size.Width = 28 + $btnBrowseWim.Size = $System_Drawing_Size + $btnBrowseWim.TabIndex = 1 + $btnBrowseWim.Text = "..." + $btnBrowseWim.UseVisualStyleBackColor = $true + $btnBrowseWim.add_Click($btnBrowseWim_OnClick) + $groupBox1.Controls.Add($btnBrowseWim) + #endregion btnBrowseWim + + $openFileDialog1.FileName = "openFileDialog1" + $openFileDialog1.ShowHelp = $true + #endregion Form Code + + # Save the initial state of the form + $InitialFormWindowState = $frmMain.WindowState + + # Init the OnLoad event to correct the initial state of the form + $frmMain.add_Load($OnLoadForm_StateCorrection) + + # Return the constructed form. + $ret = $frmMain.ShowDialog() + + if (!($ret -ilike "OK")) { + throw "Form session has been cancelled." + } + if ([string]::IsNullOrEmpty($SourcePath)) { + throw "No source path specified." + } + + # VHD Format + $VHDFormat = $cmbVhdFormat.SelectedItem + + # VHD Size + $SizeBytes = Invoke-Expression "$($numVhdSize.Value)$($cmbVhdSizeUnit.SelectedItem)" + + # Working Directory + $WorkingDirectory = $txtWorkingDirectory.Text + + # VHDPath + if (![string]::IsNullOrEmpty($txtVhdName.Text)) { + $VHDPath = "$($WorkingDirectory)\$($txtVhdName.Text)" + } + + # Edition + if (![string]::IsNullOrEmpty($cmbSkuList.SelectedItem)) { + $Edition = $cmbSkuList.SelectedItem + } + + # Because we used ShowDialog, we need to manually dispose of the form. + # This probably won't make much of a difference, but let's free up all of the resources we can + # before we start the conversion process. + $frmMain.Dispose() + } + + if ($VHDFormat -ilike "AUTO") { + if ($DiskLayout -eq "BIOS") { + $VHDFormat = "VHD" + } else { + $VHDFormat = "VHDX" + } + } + + # + # Choose smallest supported block size for dynamic VHD(X) + # + $BlockSizeBytes = 1MB + + # There's a difference between the maximum sizes for VHDs and VHDXs. Make sure we follow it. + if ("VHD" -ilike $VHDFormat) { + if ($SizeBytes -gt $vhdMaxSize) { + Write-W2VWarn "For the VHD file format, the maximum file size is ~2040GB. We're automatically setting the size to 2040GB for you." + $SizeBytes = 2040GB + } + + $BlockSizeBytes = 512KB + } + + # Check if -VHDPath and -WorkingDirectory were both specified. + if ((![string]::IsNullOrEmpty($VHDPath)) -and (![string]::IsNullOrEmpty($WorkingDirectory))) { + if ($WorkingDirectory -ne $pwd) { + # If the WorkingDirectory is anything besides $pwd, tell people that the WorkingDirectory is being ignored. + Write-W2VWarn "Specifying -VHDPath and -WorkingDirectory at the same time is contradictory." + Write-W2VWarn "Ignoring the WorkingDirectory specification." + $WorkingDirectory = Split-Path $VHDPath -Parent + } + } + if ($VHDPath) { + # Check to see if there's a conflict between the specified file extension and the VHDFormat being used. + $ext = ([IO.FileInfo]$VHDPath).Extension + + if (!($ext -ilike ".$($VHDFormat)")) { + throw "There is a mismatch between the VHDPath file extension ($($ext.ToUpper())), and the VHDFormat (.$($VHDFormat)). Please ensure that these match and try again." + } + } + + # Create a temporary name for the VHD(x). We'll name it properly at the end of the script. + if ([string]::IsNullOrEmpty($VHDPath)) { + $VHDPath = Join-Path $WorkingDirectory "$($sessionKey).$($VHDFormat.ToLower())" + } else { + # Since we can't do Resolve-Path against a file that doesn't exist, we need to get creative in determining + # the full path that the user specified (or meant to specify if they gave us a relative path). + # Check to see if the path has a root specified. If it doesn't, use the working directory. + if (![IO.Path]::IsPathRooted($VHDPath)) { + $VHDPath = Join-Path $WorkingDirectory $VHDPath + } + + $vhdFinalName = Split-Path $VHDPath -Leaf + $VHDPath = Join-Path (Split-Path $VHDPath -Parent) "$($sessionKey).$($VHDFormat.ToLower())" + } + Write-W2VTrace "Temporary $VHDFormat path is : $VHDPath" + + # If we're using an ISO, mount it and get the path to the WIM file. + if (([IO.FileInfo]$SourcePath).Extension -ilike ".ISO") { + # If the ISO isn't local, copy it down so we don't have to worry about resource contention + # or about network latency. + if (Test-IsNetworkLocation $SourcePath) { + Write-W2VError "ISO Path cannot be network location" + #Write-W2VInfo "Copying ISO $(Split-Path $SourcePath -Leaf) to temp folder..." + #robocopy $(Split-Path $SourcePath -Parent) $TempDirectory $(Split-Path $SourcePath -Leaf) | Out-Null + #$SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)" + #$tempSource = $SourcePath + } + $isoPath = (Resolve-Path $SourcePath).Path + + Write-W2VInfo "Opening ISO $(Split-Path $isoPath -Leaf)..." + <# + $openIso = Mount-DiskImage -ImagePath $isoPath -StorageType ISO -PassThru + # Refresh the DiskImage object so we can get the real information about it. I assume this is a bug. + $openIso = Get-DiskImage -ImagePath $isoPath + $driveLetter = ($openIso | Get-Volume).DriveLetter + #> + $SourcePath = "$($DriveLetter):\sources\install.wim" + + # Check to see if there's a WIM file we can muck about with. + Write-W2VInfo "Looking for $($SourcePath)..." + if (!(Test-Path $SourcePath)) { + throw "The specified ISO does not appear to be valid Windows installation media." + } + } + + # Check to see if the WIM is local, or on a network location. If the latter, copy it locally. + if (Test-IsNetworkLocation $SourcePath) { + Write-W2VInfo "Copying WIM $(Split-Path $SourcePath -Leaf) to temp folder..." + robocopy $(Split-Path $SourcePath -Parent) $TempDirectory $(Split-Path $SourcePath -Leaf) | Out-Null + $SourcePath = "$($TempDirectory)\$(Split-Path $SourcePath -Leaf)" + + $tempSource = $SourcePath + } + $SourcePath = (Resolve-Path $SourcePath).Path + Write-W2VInfo "Looking for the requested Windows image in the WIM file" + $WindowsImage = Get-WindowsImage -ImagePath "$($driveLetter):\sources\install.wim" + if (-not $WindowsImage -or ($WindowsImage -is [System.Array])) { + $EditionIndex = 0; + if ([int32]::TryParse($Edition,[ref]$EditionIndex)) { + $WindowsImage = Get-WindowsImage -ImagePath $SourcePath -Index $EditionIndex + } else { + $WindowsImage = Get-WindowsImage -ImagePath $SourcePath | Where-Object { $_.ImageName -ilike "*$($Edition)" } + } + if (-not $WindowsImage) { + throw "Requested windows Image was not found on the WIM file!" + } + if ($WindowsImage -is [System.Array]) { + Write-W2VInfo "WIM file has the following $($WindowsImage.Count) images that match filter *$($Edition)" + Get-WindowsImage -ImagePath $SourcePath + + Write-W2VError "You must specify an Edition or SKU index, since the WIM has more than one image." + throw "There are more than one images that match ImageName filter *$($Edition)" + } + } + $ImageIndex = $WindowsImage[0].ImageIndex + + # We're good. Open the WIM container. + # NOTE: this is only required because we want to get the XML-based meta-data at the end. Is there a better way? + # If we can get this information from DISM cmdlets, we can remove the openWim constructs + $openWim = New-Object WIM2VHD.WimFile $SourcePath + $openImage = $openWim[[int32]$ImageIndex] + if ($null -eq $openImage) { + Write-W2VError "The specified edition does not appear to exist in the specified WIM." + Write-W2VError "Valid edition names are:" + $openWim.Images | ForEach-Object { Write-W2VError " $($_.ImageFlags)" } + throw + } + Write-W2VInfo "Image $($openImage.ImageIndex) selected ($($openImage.ImageFlags))..." + + # Check to make sure that the image we're applying is Windows 7 or greater. + if ($openImage.ImageVersion -lt $lowestSupportedVersion) { + if ($openImage.ImageVersion -eq "0.0.0.0") { + Write-W2VWarn "The specified WIM does not encode the Windows version." + } else { + throw "Convert-WindowsImage only supports Windows 7 and Windows 8 WIM files. The specified image (version $($openImage.ImageVersion)) does not appear to contain one of those operating systems." + } + } + if ($hyperVEnabled) { + Write-W2VInfo "Creating sparse disk..." + $newVhd = New-VHD -Path $VHDPath -SizeBytes $SizeBytes -BlockSizeBytes $BlockSizeBytes -Dynamic + + Write-W2VInfo "Mounting $VHDFormat..." + $disk = $newVhd | Mount-VHD -Passthru | Get-Disk + } else { + <# + Create the VHD using the VirtDisk Win32 API. + So, why not use the New-VHD cmdlet here? + + New-VHD depends on the Hyper-V Cmdlets, which aren't installed by default. + Installing those cmdlets isn't a big deal, but they depend on the Hyper-V WMI + APIs, which in turn depend on Hyper-V. In order to prevent Convert-WindowsImage + from being dependent on Hyper-V (and thus, x64 systems only), we're using the + VirtDisk APIs directly. + #> + + Write-W2VInfo "Creating sparse disk..." + [WIM2VHD.VirtualHardDisk]::CreateSparseDisk( + $VHDFormat, + $VHDPath, + $SizeBytes, + $true + ) + # Attach the VHD.\ + Write-W2VInfo "Attaching $VHDFormat..." + $disk = Mount-DiskImage -ImagePath $VHDPath -Passthru | Get-DiskImage | Get-Disk + } + + switch ($DiskLayout) { + "BIOS" { + Write-W2VInfo "Initializing disk..." + Initialize-Disk -Number $disk.Number -PartitionStyle MBR + # + # Create the Windows/system partition + # + Write-W2VInfo "Creating single partition..." + $systemPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -MbrType IFS -IsActive + $windowsPartition = $systemPartition + Write-W2VInfo "Formatting windows volume..." + $systemVolume = Format-Volume -Partition $systemPartition -FileSystem NTFS -Force -Confirm:$false + $windowsVolume = $systemVolume + } + + "UEFI" { + Write-W2VInfo "Initializing disk..." + Initialize-Disk -Number $disk.Number -PartitionStyle GPT + if ((Get-WindowsBuildNumber) -ge 10240) { + # + # Create the system partition. Create a data partition so we can format it, then change to ESP + # + Write-W2VInfo "Creating EFI system partition..." + $systemPartition = New-Partition -DiskNumber $disk.Number -Size 200MB -GptType '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}' + Write-W2VInfo "Formatting system volume..." + $systemVolume = Format-Volume -Partition $systemPartition -FileSystem FAT32 -Force -Confirm:$false + Write-W2VInfo "Setting system partition as ESP..." + $systemPartition | Set-Partition -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' + $systemPartition | Add-PartitionAccessPath -AssignDriveLetter + } else { + # + # Create the system partition + # + Write-W2VInfo "Creating EFI system partition (ESP)..." + $systemPartition = New-Partition -DiskNumber $disk.Number -Size 200MB -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -AssignDriveLetter + Write-W2VInfo "Formatting ESP..." + $formatArgs = @( + "$($systemPartition.DriveLetter):",# Partition drive letter + "/FS:FAT32",# File system + "/Q",# Quick format + "/Y" # Suppress prompt + ) + Run-Executable -Executable format -Arguments $formatArgs + } + + # + # Create the reserved partition + # + Write-W2VInfo "Creating MSR partition..." + $reservedPartition = New-Partition -DiskNumber $disk.Number -Size 128MB -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}' + + # + # Create the Windows partition + # + Write-W2VInfo "Creating windows partition..." + $windowsPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -GptType '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}' + + Write-W2VInfo "Formatting windows volume..." + $windowsVolume = Format-Volume -Partition $windowsPartition -FileSystem NTFS -Force -Confirm:$false + } + + "WindowsToGo" { + Write-W2VInfo "Initializing disk..." + Initialize-Disk -Number $disk.Number -PartitionStyle MBR + # + # Create the system partition + # + Write-W2VInfo "Creating system partition..." + $systemPartition = New-Partition -DiskNumber $disk.Number -Size 350MB -MbrType FAT32 -IsActive + + Write-W2VInfo "Formatting system volume..." + $systemVolume = Format-Volume -Partition $systemPartition -FileSystem FAT32 -Force -Confirm:$false + # + # Create the Windows partition + # + Write-W2VInfo "Creating windows partition..." + $windowsPartition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -MbrType IFS + Write-W2VInfo "Formatting windows volume..." + $windowsVolume = Format-Volume -Partition $windowsPartition -FileSystem NTFS -Force -Confirm:$false + } + } + + # + # Assign drive letter to Windows partition. This is required for bcdboot + # + $attempts = 1 + $assigned = $false + do { + $windowsPartition | Add-PartitionAccessPath -AssignDriveLetter + $windowsPartition = $windowsPartition | Get-Partition + if ($windowsPartition.DriveLetter -ne 0) { + $assigned = $true + } else { + #sleep for up to 10 seconds and retry + Get-Random -Minimum 1 -Maximum 10 | Start-Sleep + $attempts++ + } + } while ($attempts -le 100 -and -not ($assigned)) + if (-not ($assigned)) { + throw "Unable to get Partition after retry" + } + $windowsDrive = $(Get-Partition -Volume $windowsVolume).AccessPaths[0].substring(0,2) + Write-W2VInfo "Windows path ($windowsDrive) has been assigned." + Write-W2VInfo "Windows path ($windowsDrive) took $attempts attempts to be assigned." + + # + # Refresh access paths (we have now formatted the volume) + # + $systemPartition = $systemPartition | Get-Partition + $systemDrive = $systemPartition.AccessPaths[0].trimend("\").Replace("\?","??") + Write-W2VInfo "System volume location: $systemDrive" + + #################################################################################################### + # APPLY IMAGE FROM WIM TO THE NEW VHD + #################################################################################################### + + Write-W2VInfo "Applying image to $VHDFormat. This could take a while..." + if ((Get-Command Expand-WindowsImage -ErrorAction SilentlyContinue) -and ((-not $ApplyEA) -and ([string]::IsNullOrEmpty($DismPath)))) { + Expand-WindowsImage -ApplyPath $windowsDrive -ImagePath $SourcePath -Index $ImageIndex -LogPath "$($logFolder)\DismLogs.log" | Out-Null + } else { + if (![string]::IsNullOrEmpty($DismPath)) { + $dismPath = $DismPath + } else { + $dismPath = $(Join-Path (Get-Item env:\windir).Value "system32\dism.exe") + } + + $applyImage = "/Apply-Image" + if ($ApplyEA) { + $applyImage = $applyImage + " /EA" + } + + $dismArgs = @("$applyImage /ImageFile:`"$SourcePath`" /Index:$ImageIndex /ApplyDir:$windowsDrive /LogPath:`"$($logFolder)\DismLogs.log`"") + Write-W2VInfo "Applying image: $dismPath $dismArgs" + $process = Start-Process -Passthru -Wait -NoNewWindow -FilePath $dismPath ` + -ArgumentList $dismArgs ` + + if ($process.ExitCode -ne 0) { + throw "Image Apply failed! See DismImageApply logs for details" + } + } + Write-W2VInfo "Image was applied successfully. " + + # + # Here we copy in the unattend file (if specified by the command line) + # + if (![string]::IsNullOrEmpty($UnattendPath)) { + Write-W2VInfo "Applying unattend file ($(Split-Path $UnattendPath -Leaf))..." + Copy-Item -Path $UnattendPath -Destination (Join-Path $windowsDrive "unattend.xml") -Force + } + if (![string]::IsNullOrEmpty($MergeFolderPath)) { + Write-W2VInfo "Applying merge folder ($MergeFolderPath)..." + Copy-Item -Recurse -Path (Join-Path $MergeFolderPath "*") -Destination $windowsDrive -Force #added to handle merge folders + } + if (($openImage.ImageArchitecture -ne "ARM") -and # No virtualization platform for ARM images + ($openImage.ImageArchitecture -ne "ARM64") -and # No virtualization platform for ARM64 images + ($BCDinVHD -ne "NativeBoot")) # User asked for a non-bootable image + { + if (Test-Path "$($systemDrive)\boot\bcd") { + Write-W2VInfo "Image already has BIOS BCD store..." + } elseif (Test-Path "$($systemDrive)\efi\microsoft\boot\bcd") { + Write-W2VInfo "Image already has EFI BCD store..." + } else { + Write-W2VInfo "Making image bootable..." + $bcdBootArgs = @( + "$($windowsDrive)\Windows",# Path to the \Windows on the VHD + "/s $systemDrive",# Specifies the volume letter of the drive to create the \BOOT folder on. + "/v" # Enabled verbose logging. + ) + switch ($DiskLayout) { + "BIOS" { + $bcdBootArgs += "/f BIOS" # Specifies the firmware type of the target system partition + } + "UEFI" { + $bcdBootArgs += "/f UEFI" # Specifies the firmware type of the target system partition + } + "WindowsToGo" { + # Create entries for both UEFI and BIOS if possible + if (Test-Path "$($windowsDrive)\Windows\boot\EFI\bootmgfw.efi") { + $bcdBootArgs += "/f ALL" + } + } + } + Run-Executable -Executable $BCDBoot -Arguments $bcdBootArgs + + # The following is added to mitigate the VMM diff disk handling + # We're going to change from MBRBootOption to LocateBootOption. + if ($DiskLayout -eq "BIOS") { + Write-W2VInfo "Fixing the Device ID in the BCD store on $($VHDFormat)..." + Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( + "/store $($systemDrive)\boot\bcd", + "/set `{bootmgr`} device locate" + ) + Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( + "/store $($systemDrive)\boot\bcd", + "/set `{default`} device locate" + ) + Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( + "/store $($systemDrive)\boot\bcd", + "/set `{default`} osdevice locate" + ) + } + } + Write-W2VInfo "Drive is bootable. Cleaning up..." + + # Are we turning the debugger on? + if ($EnableDebugger -inotlike "None") { + $bcdEditArgs = $null; + # Configure the specified debugging transport and other settings. + switch ($EnableDebugger) { + "Serial" { + $bcdEditArgs = @( + "/dbgsettings SERIAL", + "DEBUGPORT:$($ComPort.Value)", + "BAUDRATE:$($BaudRate.Value)" + ) + } + "1394" { + $bcdEditArgs = @( + "/dbgsettings 1394", + "CHANNEL:$($Channel.Value)" + ) + } + "USB" { + $bcdEditArgs = @( + "/dbgsettings USB", + "TARGETNAME:$($Target.Value)" + ) + } + "Local" { + $bcdEditArgs = @( + "/dbgsettings LOCAL" + ) + } + "Network" { + $bcdEditArgs = @( + "/dbgsettings NET", + "HOSTIP:$($IP.Value)", + "PORT:$($Port.Value)", + "KEY:$($Key.Value)" + ) + } + } + $bcdStores = @( + "$($systemDrive)\boot\bcd", + "$($systemDrive)\efi\microsoft\boot\bcd" + ) + foreach ($bcdStore in $bcdStores) { + if (Test-Path $bcdStore) { + Write-W2VInfo "Turning kernel debugging on in the $($VHDFormat) for $($bcdStore)..." + Run-Executable -Executable "BCDEDIT.EXE" -Arguments ( + "/store $($bcdStore)", + "/set `{default`} debug on" + ) + $bcdEditArguments = @("/store $($bcdStore)") + $bcdEditArgs + Run-Executable -Executable "BCDEDIT.EXE" -Arguments $bcdEditArguments + } + } + } + } else { + # Don't bother to check on debugging. We can't boot WoA VHDs in VMs, and + # if we're native booting, the changes need to be made to the BCD store on the + # physical computer's boot volume. + Write-W2VInfo "Image applied. It is not bootable." + } + + if ($RDP -or (-not $ExpandOnNativeBoot)) { + $hiveSystem = Mount-RegistryHive -Hive (Join-Path $windowsDrive "Windows\System32\Config\System") + if ($RDP) { + Write-W2VInfo "Enabling Remote Desktop" + Set-W2VItemProperty -Path "HKLM:\$($hiveSystem)\ControlSet001\Control\Terminal Server" -Name "fDenyTSConnections" -Value 0 + Set-W2VItemProperty -Path "HKLM:\$($hiveSystem)\ControlSet001\Control\Terminal Server\WinStations\RDP-Tcp" -Name "UserAuthentication" -Value 0 + } + if (-not $ExpandOnNativeBoot) { + Write-W2VInfo "Disabling automatic $VHDFormat expansion for Native Boot" + Set-W2VItemProperty -Path "HKLM:\$($hiveSystem)\ControlSet001\Services\FsDepends\Parameters" -Name "VirtualDiskExpandOnMount" -Value 4 + } + Dismount-RegistryHive -HiveMountPoint $hiveSystem + } + + if ($Driver) { + Write-W2VInfo "Adding Windows Drivers to the Image" + $Driver | ForEach-Object -Process { + Write-W2VInfo "Driver path: $PSItem" + Add-WindowsDriver -Path $windowsDrive -Recurse -Driver $PSItem -Verbose | Out-Null + } + } + + if ($Feature) { + Write-W2VInfo "Installing Windows Feature(s) $Feature to the Image" + $FeatureSourcePath = Join-Path -Path "$($driveLetter):" -ChildPath "sources\sxs" + Write-W2VInfo "From $FeatureSourcePath" + Enable-WindowsOptionalFeature -FeatureName $Feature -Source $FeatureSourcePath -Path $windowsDrive -All | Out-Null + } + + if ($Package) { + Write-W2VInfo "Adding Windows Packages to the Image" + $Package | ForEach-Object -Process { + Write-W2VInfo "Package path: $PSItem" + Add-WindowsPackage -Path $windowsDrive -PackagePath $PSItem | Out-Null + } + } + + # + # Remove system partition access path, if necessary + # + if (($GPUName)) { + Add-VMGpuPartitionAdapterFiles -GPUName $GPUName -DriveLetter $windowsDrive + } + + if ($Parsec -eq $true) { + Write-W2VInfo "Setting up Parsec to install at boot" + } + + if (($Parsec -eq $true) -or ($RDP -eq $true) -or ($NumLock -eq $true)) { + Setup-RemoteDesktop -Parsec:$Parsec -ParsecVDD:$ParsecVDD -DisableHVDD:$DisableHVDD -RDP:$RDP -NumLock:$NumLock -DriveLetter $WindowsDrive -Team_ID $team_id -Key $key + } + + if ($DiskLayout -eq "UEFI") { + $systemPartition | Remove-PartitionAccessPath -AccessPath $systemPartition.AccessPaths[0] + } + + if ([string]::IsNullOrEmpty($vhdFinalName)) { + # We need to generate a file name. + Write-W2VInfo "Generating name for $($VHDFormat)..." + $hive = Mount-RegistryHive -Hive (Join-Path $windowsDrive "Windows\System32\Config\Software") + $buildLabEx = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").BuildLabEx + $installType = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").InstallationType + $editionId = (Get-ItemProperty "HKLM:\$($hive)\Microsoft\Windows NT\CurrentVersion").EditionID + $skuFamily = $null + + Dismount-RegistryHive -HiveMountPoint $hive + + # Is this ServerCore? + # Since we're only doing this string comparison against the InstallType key, we won't get + # false positives with the Core SKU. + if ($installType.ToUpper().Contains("CORE")) { + $editionId += "Core" + } + + # What type of SKU are we? + if ($installType.ToUpper().Contains("SERVER")) { + $skuFamily = "Server" + } elseif ($installType.ToUpper().Contains("CLIENT")) { + $skuFamily = "Client" + } else { + $skuFamily = "Unknown" + } + + # + # ISSUE - do we want VL here? + # + $vhdFinalName = "$($buildLabEx)_$($skuFamily)_$($editionId)_$($openImage.ImageDefaultLanguage).$($VHDFormat.ToLower())" + Write-W2VTrace "$VHDFormat final name is : $vhdFinalName" + } + + if ($hyperVEnabled) { + Write-W2VInfo "Dismounting $VHDFormat..." + Dismount-VHD -Path $VHDPath + } else { + Write-W2VInfo "Closing $VHDFormat..." + Dismount-DiskImage -ImagePath $VHDPath + } + + $vhdFinalPath = Join-Path (Split-Path $VHDPath -Parent) $vhdFinalName + Write-W2VTrace "$VHDFormat final path is : $vhdFinalPath" + + if (Test-Path $vhdFinalPath) { + Write-W2VInfo "Deleting pre-existing $VHDFormat : $(Split-Path $vhdFinalPath -Leaf)..." + Remove-Item -Path $vhdFinalPath -Force + } + + Write-W2VTrace -text "Renaming $VHDFormat at $VHDPath to $vhdFinalName" + Rename-Item -Path (Resolve-Path $VHDPath).Path -NewName $vhdFinalName -Force + $vhd += Get-DiskImage -ImagePath $vhdFinalPath + + $vhdFinalName = $null + } catch { + Write-W2VError $_ + Write-W2VInfo "Log folder is $logFolder" + } finally { + # If we still have a WIM image open, close it. + if ($openWim -ne $null) { + Write-W2VInfo "Closing Windows image..." + $openWim.Close() + } + # If we still have a registry hive mounted, dismount it. + if ($mountedHive -ne $null) { + Write-W2VInfo "Closing registry hive..." + Dismount-RegistryHive -HiveMountPoint $mountedHive + } + # If VHD is mounted, unmount it + if (Test-Path $VHDPath) { + if ($hyperVEnabled) { + if ((Get-VHD -Path $VHDPath).Attached) { + Dismount-VHD -Path $VHDPath + } + } else { + Dismount-DiskImage -ImagePath $VHDPath + } + } + # If we still have an ISO open, close it. + if ($openIso -ne $null) { + Write-W2VInfo "Closing ISO..." + Dismount-DiskImage $ISOPath + } + if (-not $CacheSource) { + if ($tempSource -and (Test-Path $tempSource)) { + Remove-Item -Path $tempSource -Force + } + } + # Close out the transcript and tell the user we're done. + Dismount-ISO -SourcePath $ISOPath + if ($transcripting) { + $null = Stop-Transcript + } + } + } end { + if ($Passthru) { + return $vhd + } + } + #endregion Code + +} +#======================================================================== + +#======================================================================== +function Add-WindowsImageTypes { + $code = @" + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Runtime.InteropServices; + using System.Security; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Xml.Linq; + using System.Xml.XPath; + using Microsoft.Win32.SafeHandles; + namespace WIM2VHD { + public class NativeMethods { + #region Delegates and Callbacks + #region WIMGAPI + public delegate uint WimMessageCallback( + uint MessageId, + IntPtr wParam, + IntPtr lParam, + IntPtr UserData + ); + public static void RegisterMessageCallback(WimFileHandle hWim, WimMessageCallback callback) { + uint _callback = NativeMethods.WimRegisterMessageCallback(hWim, callback, IntPtr.Zero); + int rc = Marshal.GetLastWin32Error(); + if (0 != rc) { + throw + new InvalidOperationException( + string.Format( + CultureInfo.CurrentCulture, + "Unable to register message callback." + )); + } + } + public static void UnregisterMessageCallback(WimFileHandle hWim, WimMessageCallback registeredCallback) { + bool status = NativeMethods.WimUnregisterMessageCallback(hWim, registeredCallback); + int rc = Marshal.GetLastWin32Error(); + if (!status) { + throw + new InvalidOperationException( + string.Format( + CultureInfo.CurrentCulture, + "Unable to unregister message callback." + )); + } + } + #endregion WIMGAPI + #endregion Delegates and Callbacks + #region Constants + #region VDiskInterop + public const uint OPEN_VIRTUAL_DISK_RW_DEFAULT_DEPTH = 0x00000001; + public const uint DEFAULT_BLOCK_SIZE = 0x00080000; + public const uint DISK_SECTOR_SIZE = 0x00000200; + internal const uint ERROR_VIRTDISK_NOT_VIRTUAL_DISK = 0xC03A0015; + internal const uint ERROR_NOT_FOUND = 0x00000490; + internal const uint ERROR_IO_PENDING = 0x000003E5; + internal const uint ERROR_INSUFFICIENT_BUFFER = 0x0000007A; + internal const uint ERROR_ERROR_DEV_NOT_EXIST = 0x00000037; + internal const uint ERROR_BAD_COMMAND = 0x00000016; + internal const uint ERROR_SUCCESS = 0x00000000; + public const uint GENERIC_READ = 0x80000000; + public const uint GENERIC_WRITE = 0x40000000; + public const short FILE_ATTRIBUTE_NORMAL = 0x00000080; + public const uint CREATE_NEW = 0x00000001; + public const uint CREATE_ALWAYS = 0x00000002; + public const uint OPEN_EXISTING = 0x00000003; + public const short INVALID_HANDLE_VALUE = -1; + internal static Guid VirtualStorageTypeVendorUnknown = new Guid("00000000-0000-0000-0000-000000000000"); + internal static Guid VirtualStorageTypeVendorMicrosoft = new Guid("EC984AEC-A0F9-47e9-901F-71415A66345B"); + #endregion VDiskInterop + #region WIMGAPI + public const uint WIM_FLAG_VERIFY = 0x00000002; + public const uint WIM_FLAG_INDEX = 0x00000004; + public const uint WM_APP = 0x00008000; + #endregion WIMGAPI + #endregion Constants + #region Enums and Flags + #region VDiskInterop + public enum CreateVirtualDiskVersion : int { + VersionUnspecified = 0x00000000, + Version1 = 0x00000001, + Version2 = 0x00000002 + } + public enum OpenVirtualDiskVersion : int { + VersionUnspecified = 0x00000000, + Version1 = 0x00000001, + Version2 = 0x00000002 + } + public enum AttachVirtualDiskVersion : int { + VersionUnspecified = 0x00000000, + Version1 = 0x00000001, + Version2 = 0x00000002 + } + public enum CompactVirtualDiskVersion : int { + VersionUnspecified = 0x00000000, + Version1 = 0x00000001 + } + public enum VirtualStorageDeviceType : int { + Unknown = 0x00000000, + ISO = 0x00000001, + VHD = 0x00000002, + VHDX = 0x00000003 + } + [Flags] + public enum OpenVirtualDiskFlags { + None = 0x00000000, + NoParents = 0x00000001, + BlankFile = 0x00000002, + BootDrive = 0x00000004, + } + [Flags] + public enum VirtualDiskAccessMask { + None = 0x00000000, + AttachReadOnly = 0x00010000, + AttachReadWrite = 0x00020000, + Detach = 0x00040000, + GetInfo = 0x00080000, + Create = 0x00100000, + MetaOperations = 0x00200000, + Read = 0x000D0000, + All = 0x003F0000, + Writable = 0x00320000 + } + [Flags] + public enum CreateVirtualDiskFlags { + None = 0x00000000, + FullPhysicalAllocation = 0x00000001 + } + [Flags] + public enum AttachVirtualDiskFlags { + None = 0x00000000, + ReadOnly = 0x00000001, + NoDriveLetter = 0x00000002, + PermanentLifetime = 0x00000004, + NoLocalHost = 0x00000008 + } + [Flags] + public enum DetachVirtualDiskFlag { + None = 0x00000000 + } + [Flags] + public enum CompactVirtualDiskFlags { + None = 0x00000000, + NoZeroScan = 0x00000001, + NoBlockMoves = 0x00000002 + } + #endregion VDiskInterop + #region WIMGAPI + [FlagsAttribute] + internal enum WimCreateFileDesiredAccess : uint { + WimQuery = 0x00000000, + WimGenericRead = 0x80000000 + } + public enum WimMessage : uint { + WIM_MSG = WM_APP + 0x1476, + WIM_MSG_TEXT, + WIM_MSG_PROGRESS, + WIM_MSG_PROCESS, + WIM_MSG_SCANNING, + WIM_MSG_SETRANGE, + WIM_MSG_SETPOS, + WIM_MSG_STEPIT, + WIM_MSG_COMPRESS, + WIM_MSG_ERROR, + WIM_MSG_ALIGNMENT, + WIM_MSG_RETRY, + WIM_MSG_SPLIT, + WIM_MSG_SUCCESS = 0x00000000, + WIM_MSG_ABORT_IMAGE = 0xFFFFFFFF + } + internal enum WimCreationDisposition : uint { + WimOpenExisting = 0x00000003, + } + internal enum WimActionFlags : uint { + WimIgnored = 0x00000000 + } + internal enum WimCompressionType : uint { + WimIgnored = 0x00000000 + } + internal enum WimCreationResult : uint { + WimCreatedNew = 0x00000000, + WimOpenedExisting = 0x00000001 + } + #endregion WIMGAPI + #endregion Enums and Flags + #region Structs + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct CreateVirtualDiskParameters { + public CreateVirtualDiskVersion Version; + public Guid UniqueId; + public ulong MaximumSize; + public uint BlockSizeInBytes; + public uint SectorSizeInBytes; + public string ParentPath; + public string SourcePath; + public OpenVirtualDiskFlags OpenFlags; + public bool GetInfoOnly; + public VirtualStorageType ParentVirtualStorageType; + public VirtualStorageType SourceVirtualStorageType; + public Guid ResiliencyGuid; + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct VirtualStorageType { + public VirtualStorageDeviceType DeviceId; + public Guid VendorId; + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct SecurityDescriptor { + public byte revision; + public byte size; + public short control; + public IntPtr owner; + public IntPtr group; + public IntPtr sacl; + public IntPtr dacl; + } + #endregion Structs + #region VirtDisk.DLL P/Invoke + [DllImport("virtdisk.dll", CharSet = CharSet.Unicode)] + public static extern uint CreateVirtualDisk( + [In, Out] ref VirtualStorageType VirtualStorageType, + [In] string Path, + [In] VirtualDiskAccessMask VirtualDiskAccessMask, + [In, Out] ref SecurityDescriptor SecurityDescriptor, + [In] CreateVirtualDiskFlags Flags, + [In] uint ProviderSpecificFlags, + [In, Out] ref CreateVirtualDiskParameters Parameters, + [In] IntPtr Overlapped, + [Out] out SafeFileHandle Handle); + #endregion VirtDisk.DLL P/Invoke + #region Win32 P/Invoke + [DllImport("advapi32", SetLastError = true)] + public static extern bool InitializeSecurityDescriptor( + [Out] out SecurityDescriptor pSecurityDescriptor, + [In] uint dwRevision); + #endregion Win32 P/Invoke + #region WIMGAPI P/Invoke + #region SafeHandle wrappers for WimFileHandle and WimImageHandle + public sealed class WimFileHandle : SafeHandle { + public WimFileHandle(string wimPath) : base(IntPtr.Zero, true) { + if (String.IsNullOrEmpty(wimPath)) { + throw new ArgumentNullException("wimPath"); + } + if (!File.Exists(Path.GetFullPath(wimPath))) { + throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath); + } + NativeMethods.WimCreationResult creationResult; + this.handle = NativeMethods.WimCreateFile( + wimPath, + NativeMethods.WimCreateFileDesiredAccess.WimGenericRead, + NativeMethods.WimCreationDisposition.WimOpenExisting, + NativeMethods.WimActionFlags.WimIgnored, + NativeMethods.WimCompressionType.WimIgnored, + out creationResult + ); + if (creationResult != NativeMethods.WimCreationResult.WimOpenedExisting) { + throw new Win32Exception(); + } + if (this.handle == IntPtr.Zero) { + throw new Win32Exception(); + } + NativeMethods.WimSetTemporaryPath(this, Environment.ExpandEnvironmentVariables("%TEMP%")); + } + protected override bool ReleaseHandle() { + return NativeMethods.WimCloseHandle(this.handle); + } + public override bool IsInvalid { + get { return this.handle == IntPtr.Zero; } + } + } + public sealed class WimImageHandle : SafeHandle { + public WimImageHandle(WimFile Container, uint ImageIndex) : base(IntPtr.Zero, true) { + if (null == Container) { + throw new ArgumentNullException("Container"); + } + if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) { + throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container"); + } + if (ImageIndex > Container.ImageCount) { + throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file."); + } + this.handle = NativeMethods.WimLoadImage( + Container.Handle.DangerousGetHandle(), + ImageIndex); + } + protected override bool ReleaseHandle() { + return NativeMethods.WimCloseHandle(this.handle); + } + public override bool IsInvalid { + get { return this.handle == IntPtr.Zero; } + } + } + #endregion SafeHandle wrappers for WimFileHandle and WimImageHandle + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCreateFile")] + internal static extern IntPtr WimCreateFile( + [In, MarshalAs(UnmanagedType.LPWStr)] string WimPath, + [In] WimCreateFileDesiredAccess DesiredAccess, + [In] WimCreationDisposition CreationDisposition, + [In] WimActionFlags FlagsAndAttributes, + [In] WimCompressionType CompressionType, + [Out, Optional] out WimCreationResult CreationResult + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMCloseHandle")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool WimCloseHandle( + [In] IntPtr Handle + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMLoadImage")] + internal static extern IntPtr WimLoadImage( + [In] IntPtr Handle, + [In] uint ImageIndex + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageCount")] + internal static extern uint WimGetImageCount( + [In] WimFileHandle Handle + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMGetImageInformation")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool WimGetImageInformation( + [In] SafeHandle Handle, + [Out] out StringBuilder ImageInfo, + [Out] out uint SizeOfImageInfo + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMSetTemporaryPath")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool WimSetTemporaryPath( + [In] WimFileHandle Handle, + [In] string TempPath + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMRegisterMessageCallback", CallingConvention = CallingConvention.StdCall)] + internal static extern uint WimRegisterMessageCallback( + [In, Optional] WimFileHandle hWim, + [In] WimMessageCallback MessageProc, + [In, Optional] IntPtr ImageInfo + ); + [DllImport("Wimgapi.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "WIMUnregisterMessageCallback", CallingConvention = CallingConvention.StdCall)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool WimUnregisterMessageCallback( + [In, Optional] WimFileHandle hWim, + [In] WimMessageCallback MessageProc + ); + #endregion WIMGAPI P/Invoke + } + #region WIM Interop + public class WimFile { + internal XDocument m_xmlInfo; + internal List<WimImage> m_imageList; + private static NativeMethods.WimMessageCallback wimMessageCallback; + #region Events + public delegate void DefaultImageEventHandler(object sender, DefaultImageEventArgs e); + public delegate void ProcessFileEventHandler(object sender, ProcessFileEventArgs e); + public event ProcessFileEventHandler ProcessFileEvent; + public event DefaultImageEventHandler ProgressEvent; + public event DefaultImageEventHandler ErrorEvent; + public event DefaultImageEventHandler StepItEvent; + public event DefaultImageEventHandler SetRangeEvent; + public event DefaultImageEventHandler SetPosEvent; + #endregion Events + private enum ImageEventMessage : uint { + Progress = NativeMethods.WimMessage.WIM_MSG_PROGRESS, + Process = NativeMethods.WimMessage.WIM_MSG_PROCESS, + Compress = NativeMethods.WimMessage.WIM_MSG_COMPRESS, + Error = NativeMethods.WimMessage.WIM_MSG_ERROR, + Alignment = NativeMethods.WimMessage.WIM_MSG_ALIGNMENT, + Split = NativeMethods.WimMessage.WIM_MSG_SPLIT, + Scanning = NativeMethods.WimMessage.WIM_MSG_SCANNING, + SetRange = NativeMethods.WimMessage.WIM_MSG_SETRANGE, + SetPos = NativeMethods.WimMessage.WIM_MSG_SETPOS, + StepIt = NativeMethods.WimMessage.WIM_MSG_STEPIT, + Success = NativeMethods.WimMessage.WIM_MSG_SUCCESS, + Abort = NativeMethods.WimMessage.WIM_MSG_ABORT_IMAGE + } + private uint ImageEventMessagePump(uint MessageId, IntPtr wParam, IntPtr lParam, IntPtr UserData) { + uint status = (uint) NativeMethods.WimMessage.WIM_MSG_SUCCESS; + DefaultImageEventArgs eventArgs = new DefaultImageEventArgs(wParam, lParam, UserData); + switch ((ImageEventMessage)MessageId) { + case ImageEventMessage.Progress: + ProgressEvent(this, eventArgs); + break; + case ImageEventMessage.Process: + if (null != ProcessFileEvent) { + string fileToImage = Marshal.PtrToStringUni(wParam); + ProcessFileEventArgs fileToProcess = new ProcessFileEventArgs(fileToImage, lParam); + ProcessFileEvent(this, fileToProcess); + if (fileToProcess.Abort == true) { + status = (uint)ImageEventMessage.Abort; + } + } + break; + case ImageEventMessage.Error: + if (null != ErrorEvent) { + ErrorEvent(this, eventArgs); + } + break; + case ImageEventMessage.SetRange: + if (null != SetRangeEvent) { + SetRangeEvent(this, eventArgs); + } + break; + case ImageEventMessage.SetPos: + if (null != SetPosEvent) { + SetPosEvent(this, eventArgs); + } + break; + case ImageEventMessage.StepIt: + if (null != StepItEvent) { + StepItEvent(this, eventArgs); + } + break; + default: + break; + } + return status; + } + public WimFile(string wimPath) { + if (string.IsNullOrEmpty(wimPath)) { + throw new ArgumentNullException("wimPath"); + } + if (!File.Exists(Path.GetFullPath(wimPath))) { + throw new FileNotFoundException((new FileNotFoundException()).Message, wimPath); + } + Handle = new NativeMethods.WimFileHandle(wimPath); + } + public void Close() { + foreach (WimImage image in Images) { + image.Close(); + } + if (null != wimMessageCallback) { + NativeMethods.UnregisterMessageCallback(this.Handle, wimMessageCallback); + wimMessageCallback = null; + } + if ((!Handle.IsClosed) && (!Handle.IsInvalid)) { + Handle.Close(); + } + } + public List<WimImage> Images { + get { + if (null == m_imageList) { + int imageCount = (int)ImageCount; + m_imageList = new List<WimImage>(imageCount); + for (int i = 0; i < imageCount; i++) { + // Load up each image so it's ready for us. + m_imageList.Add( + new WimImage(this, (uint)i + 1)); + } + } + return m_imageList; + } + } + public List<string> ImageNames { + get { + List<string> nameList = new List<string>(); + foreach (WimImage image in Images) { + nameList.Add(image.ImageName); + } + return nameList; + } + } + public WimImage this[int ImageIndex] { + get { return Images[ImageIndex - 1]; } + } + public WimImage this[string ImageName] { + get { + return + Images.Where(i => ( + i.ImageName.ToUpper() == ImageName.ToUpper() || + i.ImageFlags.ToUpper() == ImageName.ToUpper() )) + .DefaultIfEmpty(null) + .FirstOrDefault<WimImage>(); + } + } + internal uint ImageCount { + get { return NativeMethods.WimGetImageCount(Handle); } + } + internal XDocument XmlInfo { + get { + if (null == m_xmlInfo) { + StringBuilder builder; + uint bytes; + if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) { + throw new Win32Exception(); + } + int charCount = (int)bytes / sizeof(char); + if (null != builder) { + // Get rid of the unicode file marker at the beginning of the XML. + builder.Remove(0, 1); + builder.EnsureCapacity(charCount - 1); + builder.Length = charCount - 1; + m_xmlInfo = XDocument.Parse(builder.ToString().Trim()); + } else { + m_xmlInfo = null; + } + } + return m_xmlInfo; + } + } + public NativeMethods.WimFileHandle Handle { + get; + private set; + } + } + public class WimImage { + internal XDocument m_xmlInfo; + public WimImage(WimFile Container, uint ImageIndex) { + if (null == Container) { + throw new ArgumentNullException("Container"); + } + if ((Container.Handle.IsClosed) || (Container.Handle.IsInvalid)) { + throw new ArgumentNullException("The handle to the WIM file has already been closed, or is invalid.", "Container"); + } + if (ImageIndex > Container.ImageCount) { + throw new ArgumentOutOfRangeException("ImageIndex", "The index does not exist in the specified WIM file."); + } + Handle = new NativeMethods.WimImageHandle(Container, ImageIndex); + } + public enum Architectures : uint { + x86 = 0x0, + ARM = 0x5, + IA64 = 0x6, + AMD64 = 0x9, + ARM64 = 0xC + } + public void Close() { + if ((!Handle.IsClosed) && (!Handle.IsInvalid)) { + Handle.Close(); + } + } + public NativeMethods.WimImageHandle Handle { + get; + private set; + } + internal XDocument XmlInfo { + get { + if (null == m_xmlInfo) { + StringBuilder builder; + uint bytes; + if (!NativeMethods.WimGetImageInformation(Handle, out builder, out bytes)) { + throw new Win32Exception(); + } + int charCount = (int)bytes / sizeof(char); + if (null != builder) { + builder.Remove(0, 1); + builder.EnsureCapacity(charCount - 1); + builder.Length = charCount - 1; + m_xmlInfo = XDocument.Parse(builder.ToString().Trim()); + } else { + m_xmlInfo = null; + } + } + return m_xmlInfo; + } + } + public string ImageIndex { + get { return XmlInfo.Element("IMAGE").Attribute("INDEX").Value; } + } + public string ImageName { + get { return XmlInfo.XPathSelectElement("/IMAGE/NAME").Value; } + } + public string ImageEditionId { + get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/EDITIONID").Value; } + } + public string ImageFlags { + get { + string flagValue = String.Empty; + try { + flagValue = XmlInfo.XPathSelectElement("/IMAGE/FLAGS").Value; + } catch { + if (String.IsNullOrEmpty(flagValue)) { + flagValue = this.ImageEditionId; + if (0 == String.Compare("serverhyper", flagValue, true)) { + flagValue = "ServerHyperCore"; + } + } + } + return flagValue; + } + } + public string ImageProductType { + get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/PRODUCTTYPE").Value; } + } + public string ImageInstallationType { + get { return XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/INSTALLATIONTYPE").Value; } + } + public string ImageDescription { + get { return XmlInfo.XPathSelectElement("/IMAGE/DESCRIPTION").Value; } + } + public ulong ImageSize { + get { return ulong.Parse(XmlInfo.XPathSelectElement("/IMAGE/TOTALBYTES").Value); } + } + public Architectures ImageArchitecture { + get { + int arch = -1; + try { + arch = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/ARCH").Value); + } catch { } + return (Architectures)arch; + } + } + public string ImageDefaultLanguage { + get { + string lang = null; + try { + lang = XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/LANGUAGES/DEFAULT").Value; + } catch { } + return lang; + } + } + public Version ImageVersion { + get { + int major = 0; + int minor = 0; + int build = 0; + int revision = 0; + try { + major = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MAJOR").Value); + minor = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/MINOR").Value); + build = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/BUILD").Value); + revision = int.Parse(XmlInfo.XPathSelectElement("/IMAGE/WINDOWS/VERSION/SPBUILD").Value); + } catch { } + return (new Version(major, minor, build, revision)); + } + } + public string ImageDisplayName { + get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYNAME").Value; } + } + public string ImageDisplayDescription { + get { return XmlInfo.XPathSelectElement("/IMAGE/DISPLAYDESCRIPTION").Value; } + } + } + public class DefaultImageEventArgs : EventArgs { + public DefaultImageEventArgs( IntPtr wideParameter, IntPtr leftParameter, IntPtr userData) { + WideParameter = wideParameter; + LeftParameter = leftParameter; + UserData = userData; + } + public IntPtr WideParameter { + get; + private set; + } + public IntPtr LeftParameter { + get; + private set; + } + public IntPtr UserData { + get; + private set; + } + } + public class ProcessFileEventArgs : EventArgs { + public ProcessFileEventArgs(string file, IntPtr skipFileFlag) { + m_FilePath = file; + m_SkipFileFlag = skipFileFlag; + } + public void SkipFile() { + byte[] byteBuffer = {0}; + int byteBufferSize = byteBuffer.Length; + Marshal.Copy(byteBuffer, 0, m_SkipFileFlag, byteBufferSize); + } + public string FilePath { + get { + string stringToReturn = ""; + if (m_FilePath != null) { + stringToReturn = m_FilePath; + } + return stringToReturn; + } + } + public bool Abort { + set { m_Abort = value; } + get { return m_Abort; } + } + private string m_FilePath; + private bool m_Abort; + private IntPtr m_SkipFileFlag; + } + #endregion WIM Interop + #region VHD Interop + public class VirtualHardDisk { + #region Static Methods + #region Sparse Disks + public static void CreateSparseDisk(NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType, string path, ulong size, bool overwrite) { + CreateSparseDisk( + path, + size, + overwrite, + null, + IntPtr.Zero, + (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD) ? NativeMethods.DEFAULT_BLOCK_SIZE : 0, + virtualStorageDeviceType, + NativeMethods.DISK_SECTOR_SIZE + ); + } + public static void CreateSparseDisk( + string path, + ulong size, + bool overwrite, + string source, + IntPtr overlapped, + uint blockSizeInBytes, + NativeMethods.VirtualStorageDeviceType virtualStorageDeviceType, + uint sectorSizeInBytes) { + if (virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHD && virtualStorageDeviceType != NativeMethods.VirtualStorageDeviceType.VHDX){ + throw ( + new ArgumentOutOfRangeException( + "virtualStorageDeviceType", + virtualStorageDeviceType, + "VirtualStorageDeviceType must be VHD or VHDX." + )); + } + if ((size % NativeMethods.DISK_SECTOR_SIZE) != 0) { + throw ( + new ArgumentOutOfRangeException( + "size", + size, + "The size of the virtual disk must be a multiple of 512." + )); + } + if ((!String.IsNullOrEmpty(source)) && (!System.IO.File.Exists(source))) { + throw ( + new System.IO.FileNotFoundException( + "Unable to find the source file.", + source + )); + } + if ((overwrite) && (System.IO.File.Exists(path))) { + System.IO.File.Delete(path); + } + NativeMethods.CreateVirtualDiskParameters createParams = new NativeMethods.CreateVirtualDiskParameters(); + createParams.Version = (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD) + ? NativeMethods.CreateVirtualDiskVersion.Version1 + : NativeMethods.CreateVirtualDiskVersion.Version2; + createParams.UniqueId = Guid.NewGuid(); + createParams.MaximumSize = size; + createParams.BlockSizeInBytes = blockSizeInBytes; + createParams.SectorSizeInBytes = sectorSizeInBytes; + createParams.ParentPath = null; + createParams.SourcePath = source; + createParams.OpenFlags = NativeMethods.OpenVirtualDiskFlags.None; + createParams.GetInfoOnly = false; + createParams.ParentVirtualStorageType = new NativeMethods.VirtualStorageType(); + createParams.SourceVirtualStorageType = new NativeMethods.VirtualStorageType(); + NativeMethods.SecurityDescriptor securityDescriptor; + if (!NativeMethods.InitializeSecurityDescriptor(out securityDescriptor, 1)) { + throw ( + new SecurityException( + "Unable to initialize the security descriptor for the virtual disk." + )); + } + NativeMethods.VirtualStorageType virtualStorageType = new NativeMethods.VirtualStorageType(); + virtualStorageType.DeviceId = virtualStorageDeviceType; + virtualStorageType.VendorId = NativeMethods.VirtualStorageTypeVendorMicrosoft; + SafeFileHandle vhdHandle; + uint returnCode = NativeMethods.CreateVirtualDisk( + ref virtualStorageType, + path, + (virtualStorageDeviceType == NativeMethods.VirtualStorageDeviceType.VHD) + ? NativeMethods.VirtualDiskAccessMask.All + : NativeMethods.VirtualDiskAccessMask.None, + ref securityDescriptor, + NativeMethods.CreateVirtualDiskFlags.None, + 0, + ref createParams, + overlapped, + out vhdHandle); + vhdHandle.Close(); + if (NativeMethods.ERROR_SUCCESS != returnCode && NativeMethods.ERROR_IO_PENDING != returnCode) { + throw ( + new Win32Exception( + (int)returnCode + )); + } + } + #endregion Sparse Disks + #endregion Static Methods + } + #endregion VHD Interop + } +"@ + #ifdef for Powershell V7 or greater which looks for assemblies in same path as powershell dll path + if ($PSVersionTable.psversion.Major -ge 7) { + Add-Type -TypeDefinition $code -ErrorAction SilentlyContinue + } else { + Add-Type -TypeDefinition $code -ReferencedAssemblies "System.Xml","System.Linq","System.Xml.Linq" -ErrorAction SilentlyContinue + } +} +#======================================================================== + +#======================================================================== +function Modify-AutoUnattend { + param ( + [string]$username, + [string]$password, + [string]$autologon, + [string]$hostname, + [xml]$xml + ) + + ($xml.unattend.settings.component | where-object {$_.autologon}).autologon.password.value = $password + ($xml.unattend.settings.component | where-object {$_.autologon}).autologon.username = $username + ($xml.unattend.settings.component | where-object {$_.autologon}).autologon.enabled = $autologon + ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.Group = "Administrators" + ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.Name = $username + ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.DisplayName = $username + ($xml.unattend.settings.component | where-object {$_.UserAccounts}).UserAccounts.LocalAccounts.localaccount.Password.Value = $password + ($xml.unattend.settings.component | where-object {$_.Computername}).Computername = $hostname + ($xml.unattend.settings.component | where-object {$_.FirstLogonCommands}).FirstLogonCommands.LastChild.CommandLine = "cmd /C wmic useraccount where name=""$($username)"" set PasswordExpires=false" + + if ($CopyRegionalSettings -eq $true) { + # Get HostOS Regional Settings + $GeoId = [int32]((Get-WinHomeLocation | Select-Object -Property *).GeoId) + $TimeZone = [string]((Get-TimeZone).Id) + $SytemLocale = [string](Get-WinSystemLocale) + $UserLocale = [string]((Get-Culture | Select-Object -Property *).Name) + $LanguageTags = "$([string]([string[]]((Get-WinUserLanguageList).LanguageTag) | %{"$_;"}) -replace "".$"")" + $InputMethodTips = "$([string]([string[]]((Get-WinUserLanguageList).InputMethodTips) | %{"$_;"}) -replace "".$"")" + $DefaultMethodTip = [string]((Get-WinDefaultInputMethodOverride | Select-Object -Property *).InputMethodTip) + # Set autounattend.xml Regional Settings associated paramemetrs + $xml.GetElementsByTagName('TimeZone') | %{$_.'#text' = $TimeZone} + $xml.GetElementsByTagName('UILanguage') | %{$_.'#text' = $UserLocale} + $xml.GetElementsByTagName('UserLocale') | %{$_.'#text' = $UserLocale} + $xml.GetElementsByTagName('InputLocale') | %{$_.'#text' = $InputMethodTips} + $xml.GetElementsByTagName('SystemLocale') | %{$_.'#text' = $SytemLocale} + $xml.GetElementsByTagName('UILanguageFallback') | %{$_.'#text' = $SytemLocale} + } + $UnattendPath = New-TemporaryFile + $xml.Save("$UnattendPath") + return $UnattendPath +} +#======================================================================== + +#======================================================================== +function Get-WindowsCompatibleOS { + $build = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' + if ($build.CurrentBuild -ge 19041 -and ($($build.editionid -like 'Professional*') -or $($build.editionid -like 'Enterprise*') -or $($build.editionid -like 'Education*') -or $($build.editionid -like 'Education*') -or $($build.ProductName -like 'Windows Server 2022*'))) { + $Global:ServerOS = $($build.ProductName -like 'Windows Server 2022*') + return $true + } else { + Write-Warning "Only Windows 10 20H1 or Windows 11 or Server 2022 is supported" + } +} +#======================================================================== + +#======================================================================== +function Get-HyperVEnabled { + if ((Get-WindowsOptionalFeature -Online | Where-Object FeatureName -Like 'Microsoft-Hyper-V-All') -or (Get-WindowsOptionalFeature -Online | Where-Object FeatureName -Like 'Microsoft-Hyper-V-Online')) { + return $true + } else { + Write-Warning "You need to enable Virtualisation in your motherboard and then add the Hyper-V Windows Feature and reboot" + return $false + } +} +#======================================================================== + +#======================================================================== +function Get-WSLEnabled { + if ((wsl -l -v)[2].length -gt 1 ) { + Write-Warning "WSL is Enabled. This may interferre with GPU-P and produce an error 43 in the VM" + return $true + } else { + return $false + } +} +#======================================================================== + +#======================================================================== +function Get-VMAvailable { + $VMs = Get-VM + if ($VMs.length -eq 0) { + Write-Host "There is no an available VM to proceed. Create a VM and run script again" -ForegroundColor Yellow + return $false + } else { + return $true + } +} +#======================================================================== + +#======================================================================== +function Get-VMGpuPartitionAdapterFriendlyName { + param([switch]$GetPassedGPU) + $PassingThroguhRequired = $false + if ($GetPassedGPU -eq $true) { + try { + $DeviceID = (Get-VMGpuPartitionAdapter -VM $Global:VM | %{$_.InstancePath.split('#')})[1] + $params.GPUName = (Get-WmiObject Win32_PNPSignedDriver | where {($_.HardwareID -eq "PCI\$($DeviceID)")}).DeviceName + return $PassingThroguhRequired + } catch { + Write-Warning "There is no a GPU passed through to $($Global:VM.Name)." + $VMParam = New-VMParameter -name 'Null' -title "Pass through GPU to VM and copy host drivers? [Y/N]" -AllowedValues @{Y = $true; N = $false} + if ((Get-VMParam -VMParam $VMParam) -eq $true) { + $PassingThroguhRequired = $true + } else { + SmartExit + } + } + } + $Devices = (Get-WmiObject -Class "Msvm_PartitionableGpu" -ComputerName $env:COMPUTERNAME -Namespace "ROOT\virtualization\v2").name + $GPUs = New-Object System.Collections.Generic.List[System.Object] + Write-Host "Printing a list of compatible GPUs... It may take a while..." -ForegroundColor Yellow + $i = 0 + $GPUs.Add("AUTO") + Write-Host "0: AUTO" + foreach ($GPU in $Devices) { + $GPUname = (Get-WmiObject Win32_PNPSignedDriver | where {($_.HardwareID -eq "PCI\$($GPU.Split('#')[1])")}).DeviceName + Write-Host "$([string](++$i)): $($GPUname)" + $GPUs.Add($GPUname); + } + $m = "Select GPU ID [default: 0] (press `"Return`" to default)" + while ($true) { + try { + $s = Read-Host -Prompt $m + if (([decimal]($s) -ge 0) -and ([decimal]($s) -le $i) -and ($s.length -ne 0)) { + break + } + } catch { + $s = -1 + } + if ($s.length -eq 0) { + $s = 0 + break + } + } + $params.GPUName = $GPUs[[decimal]($s)] + return $PassingThroguhRequired +} +#======================================================================== + +#======================================================================== +function Get-VMObjects { + $VMs = New-Object System.Collections.Generic.List[System.Object] + $i = 0 + Write-Host "Printing a list of VMs..." -ForegroundColor Yellow + Foreach ($VM in Get-VM) { + Write-Host "$([string](++$i)): $($VM.Name)" + $VMs.Add($VM) + } + $m = "Select VM ID from 1 to $($i)" + while ($true) { + try { + $s = Read-Host -Prompt $m + if (([decimal]($s) -ge 1) -and ([decimal]($s) -le $i) -and ($s.length -ne 0)) { + break + } + } catch { + $s = -1 + } + } + + $Global:VM = $VMs[[decimal]($s)-1] + $Global:VHD = $Global:VM | Get-VMHardDiskDrive + $Global:StateWasRunning = $Global:VM.state -eq "Running" + + if ($Global:VM.state -ne "Off") { + Write-Host "Attemping to shutdown VM" + Stop-VM -Name $Global:VM.Name -Force -ErrorAction SilentlyContinue + While ((Get-VM $Global:VM.Name).State -ne "Off") { + Write-W2VInProgress "Waiting for VM to shutdown - make sure there are no unsaved documents" + Start-Sleep -s 1 + } + Stop-VM -Name $Global:VM.Name -TurnOff -Force -ErrorAction SilentlyContinue + } +} +#======================================================================== + +#======================================================================== +function Add-VMGpuPartitionAdapterFiles { + param( + [string]$hostname = $ENV:COMPUTERNAME, + [string]$DriveLetter, + [string]$GPUName + ) + + If (!($DriveLetter -like "*:*")) { $DriveLetter += ":" } + + If ($GPUName -eq "AUTO") { + $PartitionableGPUList = Get-WmiObject -Class "Msvm_PartitionableGpu" -ComputerName $env:COMPUTERNAME -Namespace "ROOT\virtualization\v2" + $DevicePathName = $PartitionableGPUList.Name | Select-Object -First 1 + $GPU = Get-PnpDevice | Where-Object {($_.DeviceID -like "*$($DevicePathName.Substring(8,16))*") -and ($_.Status -eq "OK")} | Select-Object -First 1 + $GPUName = $GPU.Friendlyname + $GPUServiceName = $GPU.Service + } else { + $GPU = Get-PnpDevice | Where-Object {($_.Name -eq "$GPUName") -and ($_.Status -eq "OK")} | Select-Object -First 1 + $GPUServiceName = $GPU.Service + } + # Get Third Party drivers used, that are not provided by Microsoft and presumably included in the OS + + Write-W2VInfo "Finding and copying driver files for $GPUName to VM. This could take a while..." + + $Drivers = Get-WmiObject Win32_PNPSignedDriver | where {$_.DeviceName -eq "$GPUName"} + + New-Item -ItemType Directory -Path "$DriveLetter\windows\system32\HostDriverStore" -Force | Out-Null + + #copy directory associated with sys file + $servicePath = (Get-WmiObject Win32_SystemDriver | Where-Object {$_.Name -eq "$GPUServiceName"}).Pathname + $ServiceDriverDir = $servicepath.split('\')[0..5] -join('\') + $ServicedriverDest = ("$($driveletter)\$($servicepath.split('\')[1..5] -join('\'))").Replace("DriverStore","HostDriverStore") + if (!(Test-Path $ServicedriverDest)) { + Copy-item -path "$ServiceDriverDir" -Destination "$ServicedriverDest" -Recurse + } + + # Initialize the list of detected driver packages as an array + $DriverFolders = @() + foreach ($d in $drivers) { + $DriverFiles = @() + $ModifiedDeviceID = $d.DeviceID -replace "\\", "\\" + $Antecedent = "\\$($hostname)\ROOT\cimv2:Win32_PNPSignedDriver.DeviceID=""$ModifiedDeviceID""" + $DriverFiles += Get-WmiObject Win32_PNPSignedDriverCIMDataFile -ErrorAction SilentlyContinue | where {$_.Antecedent -eq $Antecedent} + $DriverName = $d.DeviceName + $DriverID = $d.DeviceID + if ($DriverName -like "NVIDIA*") { + New-Item -ItemType Directory -Path "$driveletter\Windows\System32\drivers\Nvidia Corporation\" -Force | Out-Null + } + foreach ($i in $DriverFiles) { + $path = $i.Dependent.Split("=")[1] -replace '\\\\', '\' + $path2 = $path.Substring(1,$path.Length-2) + $InfItem = Get-Item -Path $path2 + $Version = $InfItem.VersionInfo.FileVersion + If ($path2 -like "c:\windows\system32\driverstore\*") { + $DriverDir = $path2.split('\')[0..5] -join('\') + $driverDest = ("$($driveletter)\$($path2.split('\')[1..5] -join('\'))").Replace("driverstore","HostDriverStore") + if (!(Test-Path $driverDest)) { + Copy-item -path "$DriverDir" -Destination "$driverDest" -Recurse + } + } else { + $ParseDestination = $path2.Replace("c:", "$driveletter") + $Destination = $ParseDestination.Substring(0, $ParseDestination.LastIndexOf('\')) + if (!$(Test-Path -Path $Destination)) { + New-Item -ItemType Directory -Path $Destination -Force | Out-Null + } + Copy-Item $path2 -Destination $Destination -Force + } + } + } + +} +#======================================================================== + +#======================================================================== +function Copy-GPUDrivers { + param() + Write-Host "`r`nMounting Drive..." + $params.DriveLetter = (Mount-VHD -Path $Global:VHD.Path -PassThru | Get-Disk | Get-Partition | Get-Volume | Where-Object {$_.DriveLetter} | ForEach-Object DriveLetter) | where { Test-Path "$_`:\Windows\System32" } + Add-VMGpuPartitionAdapterFiles -DriveLetter $params.DriveLetter -GPUName $params.GPUName + Write-Host "Dismounting Drive..." + Dismount-VHD -Path $Global:VHD.Path +} +#======================================================================== + +#======================================================================== +function Delete-VMGPUPartitionAdapter { + param() + $VMName = $Global:VM.Name + foreach($Adapter in $Global:VM | Get-VMGPUPartitionAdapter) { + Remove-VMGpuPartitionAdapter -VM $Global:VM + } +} +#======================================================================== + +#======================================================================== +function Pass-VMGPUPartitionAdapter { + param ( + [switch]$OnlyResources = $false + ) + $VMName = $Global:VM.Name + $GPUName = $params.GPUName + $DedicatedPercentage = $params.GPUDedicatedResourcePercentage + + $PartitionableGPUList = Get-WmiObject -Class "Msvm_PartitionableGpu" -ComputerName $env:COMPUTERNAME -Namespace "ROOT\virtualization\v2" + if ($OnlyResources -ne $true) { + if ($GPUName -eq "AUTO") { + $DevicePathName = $PartitionableGPUList.Name[0] + $Global:VM | Add-VMGpuPartitionAdapter + } else { + $DeviceID = ((Get-WmiObject Win32_PNPSignedDriver | where {($_.Devicename -eq "$GPUNAME")}).hardwareid).split('\')[1] + $DevicePathName = ($PartitionableGPUList | Where-Object name -like "*$deviceid*").Name + $Global:VM | Add-VMGpuPartitionAdapter -InstancePath $DevicePathName + } + } + [float]$div = [math]::round($(100 / $DedicatedPercentage), 2) + $Global:VM | Set-VMGpuPartitionAdapter -MinPartitionVRAM ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -MaxPartitionVRAM ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -OptimalPartitionVRAM ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGPUPartitionAdapter -MinPartitionEncode ([math]::round($(18446744073709551615 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -MaxPartitionEncode ([math]::round($(18446744073709551615 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -OptimalPartitionEncode ([math]::round($(18446744073709551615 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -MinPartitionDecode ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -MaxPartitionDecode ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -OptimalPartitionDecode ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -MinPartitionCompute ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -MaxPartitionCompute ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VMGpuPartitionAdapter -OptimalPartitionCompute ([math]::round($(1000000000 / $div))) + $Global:VM | Set-VM -GuestControlledCacheTypes:$true +} +#======================================================================== + +#======================================================================== +function Get-Action { + param() + Write-Host "`r`nAvailable actions:" -ForegroundColor Yellow + Write-Host "1: Create new VM with GPU acceleration" + Write-Host "2: Pass through GPU acceleration to HyperV VM (GPU drivers are copied automatically)" + Write-Host "3: Upgrade VMs GPU Drivers" + Write-Host "4: Remove GPU acceleration from HyperV VM" + Write-Host "5: Change dedicated resources percentage of passed through GPU" + Write-Host "6: Exit" + $m = "`r`nSelect an action from 1 to 6" + while ($true) { + try { + $s = Read-Host -Prompt $m + if (([decimal]($s) -ge 1) -and ([decimal]($s) -le 6) -and ($s.length -ne 0)) { + break + } + } catch { + $s = -1 + } + } + switch ($s) { + 1 { break } + 6 { SmartExit } + default { if (!(Get-VMAvailable)) { SmartExit } break } + } + return $s +} +#======================================================================== + +#======================================================================== +function Get-RemoteDesktopApp { + param() + Write-Host "Available Remote Desktop apps:" -ForegroundColor Yellow + Write-Host "1: Parsec (proprietary app mostly for gaming)" + Write-Host "2: RDP (less performance 3D Acceleration than Parsec provides)" + Write-Host "3: Parsec & RDP" + Write-Host "4: None of them" + if (($params.Parsec -eq $true) -and ($params.RDP -eq $false)) { + $d = 1 + } elseif (($params.Parsec -eq $false) -and ($params.RDP -eq $true)) { + $d = 2 + } elseif (($params.Parsec -eq $true) -and ($params.RDP -eq $true)) { + $d = 3 + } else { + $d = 4 + } + $m = "Select an app you're going to use in VM [default: $d] (Press `"Return`" to default}" + while ($true) { + try { + $s = Read-Host -Prompt $m + if (([decimal]($s) -ge 1) -and ([decimal]($s) -le 4) -and ($s.length -ne 0)) { + break + } + } catch { + $s = -1 + } + if ($s.length -eq 0) { + $s = $d + break + } + } + switch ($s) { + 1 { $params.RDP = $false; $params.Parsec = $true } + 2 { $params.RDP = $true; $params.Parsec = $false } + 3 { $params.RDP = $true; $params.Parsec = $true } + 4 { $params.RDP = $false; $params.Parsec = $false } + } +} +#======================================================================== + +#======================================================================== +function Set-ServerOSGroupPolicies { + param() + $path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\HyperV" + Set-W2VItemProperty -Path $path -Name "RequireSecureDeviceAssignment" -Value 0 -PropertyType "DWORD" + Set-W2VItemProperty -Path $path -Name "RequireSupportedDeviceAssignment" -Value 0 -PropertyType "DWORD" +} +#======================================================================== + +#======================================================================== +function Open-ISOImageDialog { + param() + Write-Host "A GUI dialog is available to help you select the Gest OS Windows disk image ISO." + Add-Type -AssemblyName System.Windows.Forms + + $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog + $FileBrowser.Filter = "Windows Disk Image (ISO)|*.iso" + $FileBrowser.RestoreDirectory = $true + $FileBrowser.MultiSelect = $false; + $FileBrowser.Title = "Select Windows Disk Image ISO for VM Guest OS" + + if ($FileBrowser.ShowDialog() -eq "OK") { + $params.SourcePath = $FileBrowser.FileName -replace "\[", "``[" -replace "\]", "``]" + Write-Host "Windows Disk Image (ISO) path: ""$($FileBrowser.FileName)""" + } else { + Write-Warning "Error: You have to select Guest OS Windows Disk Image ISO." + SmartExit + } + return $params.SourcePath +} +#======================================================================== + +#======================================================================== +function Open-VHDFolderDialog { + param() + Add-Type -AssemblyName System.Windows.Forms + + $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog + $FolderBrowser.Description = "Select VM virtual hard disk location" + $FolderBrowser.RootFolder = "MyComputer" + $FolderBrowser.SelectedPath = Get-VMHost | Select-Object VirtualHardDiskPath -ExpandProperty VirtualHardDiskPath + + if ($FolderBrowser.ShowDialog() -eq "OK") { + $params.VHDPath = "$($FolderBrowser.SelectedPath)\$($params.VMName)\Virtual Hard Disks" + } else { + Write-Warning "You didn't select VM virtual hard disk location. Default is used" + $params.VHDPath = Get-VMHost | Select-Object VirtualHardDiskPath -ExpandProperty VirtualHardDiskPath + } + Write-W2VInfo "VM virtual hard disk location: ""$($params.VHDPath)""" -ForegroundColor Yellow +} +#======================================================================== + +#======================================================================== +function Open-VMFolderDialog { + param() + Add-Type -AssemblyName System.Windows.Forms + + $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog + $FolderBrowser.Description = "Select Virtual Machine files location" + $FolderBrowser.RootFolder = "MyComputer" + $FolderBrowser.SelectedPath = Get-VMHost | Select-Object VirtualMachinePath -ExpandProperty VirtualMachinePath + + if ($FolderBrowser.ShowDialog() -eq "OK") { + $params.VMPath = $FolderBrowser.SelectedPath + } else { + Write-Warning "You didn't select Virtual Machine files location. Default is used." + $params.VMPath = Get-VMHost | Select-Object VirtualMachinePath -ExpandProperty VirtualMachinePath + } + Write-W2VInfo "Virtual Machine files location: ""$($params.VMPath)\$($params.VMName)""" -ForegroundColor Yellow +} +#======================================================================== + +#======================================================================== +function Get-GuestOSCredentials{ + param() + while ($true) { + [string]$UserName = Read-Host -Prompt "Enter username" + if ($UserName.length -eq 0) { + Write-Warning "username can't be empty" + } else { + break; + } + } + while ($true) { + $SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString + $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword) + $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) + + $ReenteredSecurePassword = Read-Host -Prompt "Reenter password" -AsSecureString + $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReenteredSecurePassword) + $ReenteredPlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) + + if ($PlainPassword -eq $ReenteredPlainPassword) { + break + } else { + Write-Warning "password confirmation doesn't match" + } + } + $params.UserName = $UserName + $params.Password = $PlainPassword +} +#======================================================================== + +#======================================================================== +function Get-VMName { + param() + while ($true) { + [string]$VMName = Read-Host -Prompt "Enter Virtual Machine name" + if ($VMName.length -eq 0) { + Write-Warning "Virtual Machine name can't be empty" + } else { + break; + } + } + $params.VMName = $VMName +} +#======================================================================== + +#======================================================================== +function Get-GPUDedicatedResourcePercentage { + param() + $VMParam = New-VMParameter -name 'GPUDedicatedResourcePercentage' -title "Specify the percentage of dedicated VM GPU resource to pass [default: $($params.GPUDedicatedResourcePercentage)] (press `"Return`" to default)" -range @(5, 100) -AllowNull + $null = Get-VMParam -VMParam $VMParam +} +#======================================================================== + +#======================================================================== +function Get-HyperVSwitchAdapter { + param() + Write-Host "Available Virtual Network Switches..." -ForegroundColor Yellow + $Switches = Get-VMSwitch | Select-Object -Property SwitchType, Name + $count = 0 + $Switches | %{$count++} + switch ($count) { + 0 { $Name = 'Default Switch' + Write-Warning "There isn't any Virtual Network Switch" + break } + 1 { $Name = $Switches[0].Name + Write-W2VInfo "There is only one Virtual Network Switch: $($Switches[0] | Select-Object -Property Name -ExpandProperty Name)" + break } + default { + $i = 0 + foreach ($switch in $Switches) { + Write-Host "$([string](++$i)): [$($switch | Select-Object -Property Name -ExpandProperty SwitchType)] $($switch | Select-Object -Property Name -ExpandProperty Name)" + } + $VMParam = New-VMParameter -name 'VSIndex' -title "Select Virtual Network Switch (press `"Return`" to default)" -range @(1, $Count + 1) -rangeIsHidden -AllowNull + $s = Get-VMParam -VMParam $VMParam + if ($s.length -eq 0) { + $Name = 'Default Switch' + } else { + $Name = $Switches[$s-1].Name + } + } + } + $params.NetworkSwitch = $Name + return $Name +} +#======================================================================== + +#======================================================================== +function Set-CorrectHyperVSwitchAdapterDialog { + param( + [parameter(Mandatory = $true)][string]$Name + ) + $Switch = Get-VMSwitch | Where-Object Name -eq $Name + if (($Name -ne 'Default Switch') ) { + $VMParam = New-VMParameter -name 'VMChangeQuery' -title "Set Virtual Network switch to external bridged network mode [Y/N] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + $result = Get-VMParam -VMParam $VMParam + if ($result -eq $true) { + Set-CorrectHyperVExternalSwitchAdapter -Name $Name -SuspendOutput + } + } +} +#======================================================================== + +#======================================================================== +function Set-CorrectHyperVExternalSwitchAdapter { + param ( + [parameter(Mandatory = $true)][string]$Name, + [switch]$SuspendOutput = $false + ) + if ($Name -ne 'Default Switch') { + #retrieve external switch(es) and get Network adapter with Up state + $externalswitch = Get-VMSwitch | Where-Object Name -eq $Name + $connectedadapter = Get-NetAdapter | Where-Object Status -eq Up | Sort-Object ifIndex | Where-Object {$_.Name -NotMatch 'vEthernet' -and $_.Name -notmatch 'Network Bridge'} | Select-Object -First 1 + #Set VMSwitch(es) properties so that the connected adapter is configured + try { + Set-VMSwitch $externalswitch.Name -NetAdapterName $connectedadapter.Name -AllowManagementOS:$true -ErrorAction Stop + if ($suspendOutput -ne $true) { + Write-Host ("Reconfiguring External Hyper-V Switch {0} to use Network Adapter {1}" -f $Name, $connectedadapter.Name) -ForegroundColor Green + } + } catch { + Write-Warning ("Failed reconfiguring External Hyper-V Switch {0} to use Network Adapter {1}" -f $Name, $connectedadapter.Name) + } + } +} +#======================================================================== + +#======================================================================== +function New-VMParameter { + param ( + [string]$name, + [string]$title, + [int64[]]$range, + [switch]$rangeIsHidden = $false, + [System.Object]$AllowedValues, + [switch]$AllowNull = $false + ) + return ([PSCustomObject]@{ + name = $name + title = $title + range = $range + rangeIsHidden = $rangeIsHidden + AllowedValues = $AllowedValues + AllowNull = $AllowNull + }) +} +#======================================================================== + +#======================================================================== +function Get-VMParam { + param ( + [System.Object]$VMParam + ) + + if ($VMParam.range.count -ne 0) { + $RangeMode = $true + if ($VMParam.range[1] -gt 1Gb) { + $min = $VMParam.range[0] / 1Gb + $max = $VMParam.range[1] / 1Gb + $mul = 1Gb + if ($VMParam.rangeIsHidden -ne $true) { + $VMParam.title += ' [range:' + $min + 'GB...' + $max + 'GB]' + } + } else { + $min = $VMParam.range[0] + $max = $VMParam.range[1] + $mul = 1 + if ($VMParam.rangeIsHidden -ne $true) { + $VMParam.title += ' [range:' + $min + '...' + $max + ']' + } + } + } else { + if ($VMParam.AllowedValues.count -eq 0) { + if ($params.ContainsKey($VMParam.name)) { + return $params[$VMParam.name] + } else { + return $null + } + } + $Valid = $false + } + + while ($true) { + $p = Read-Host -Prompt $VMParam.title + if ($RangeMode) { + try { + if ([int64]($p) -gt 1Gb) { + $p /= 1Gb + } + if (([int64]($p) -ge $min) -and ([int64]($p) -le $max) -and ($p.length -ne 0)) { + [int64]($p) *= $mul + break + } + } catch { + $p = $min - 1 + } + } else { + foreach ($item in $VMParam.AllowedValues.GetEnumerator()) { + if ($p -like [string]($item.key)) { + $valid = $true + $p = $item.value + } + } + if ($valid) { + break + } + } + if ($VMParam.AllowNull -and $p.Length -eq 0) { + return $p + } + } + + if ($params.ContainsKey($VMParam.name)) { + $params[$VMParam.name] = $p + } + return $p +} +#======================================================================== + +#======================================================================== +function BoolToYesNo { + param([bool]$value) + if ($value -eq $true) { + return 'Y' + } else { + return 'N' + } +} +#======================================================================== + +#======================================================================== +function Get-VMParams { + param() + + Get-VMName + + Write-Host "Virtual Machine files location: ""$(Get-VMHost | Select-Object VirtualMachinePath -ExpandProperty VirtualMachinePath)""" -ForegroundColor Yellow + $VMParam = New-VMParameter -name 'Null' -title "Change default Virtual Machine files location? [Y/N] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + if ((Get-VMParam -VMParam $VMParam) -eq $true) { + $null = Open-VMFolderDialog + } else { + $params.VMPath = Get-VMHost | Select-Object VirtualMachinePath -ExpandProperty VirtualMachinePath + } + + Write-Host "VM virtual hard disk location: ""$(Get-VMHost | Select-Object VirtualHardDiskPath -ExpandProperty VirtualHardDiskPath)""" -ForegroundColor Yellow + $VMParam = New-VMParameter -name 'Null' -title "Change default VM virtual hard disk location? [Y/N] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + if ((Get-VMParam -VMParam $VMParam) -eq $true) { + $null = Open-VHDFolderDialog + } else { + $params.VHDPath = Get-VMHost | Select-Object VirtualHardDiskPath -ExpandProperty VirtualHardDiskPath + } + + $VMParam = New-VMParameter -name 'SizeBytes' -title "Specify VM virtual hard disk size [default: $($params.SizeBytes / 1Gb)GB] (press `"Return`" to default)" -range @(24Gb, 1024Gb) -AllowNull + $null = Get-VMParam -VMParam $VMParam + + $VMParam = New-VMParameter -name 'MemoryAmount' -title "Specify amount of RAM dedicated for VM [default: $($params.MemoryAmount / 1Gb)GB] (press `"Return`" to default)" -range @(2Gb, (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum) -AllowNull + $null = Get-VMParam -VMParam $VMParam + + $VMParam = New-VMParameter -name 'DynamicMemoryEnabled' -title "Enable Dynamic Memory? [Y/N] [default: $(BoolToYesNo $params.DynamicMemoryEnabled)] (press `"Return`" to enable)" -AllowedValues @{Y = $true; N = $false} -AllowNull + $null = Get-VMParam -VMParam $VMParam + if ($params.DynamicMemoryEnabled -eq $true) { + $VMParam = New-VMParameter -name 'MemoryMaximum' -title "Specify maximum amount of dynamic RAM dedicated for VM [default: $(($params.MemoryMaximum / 1Gb))GB] (press `"Return`" to default)" -range @($params.MemoryAmount, 128Gb) -AllowNull + $null = Get-VMParam -VMParam $VMParam + } + + $VMParam = New-VMParameter -name 'CPUCores' -title "Specify Number of virtual proccesosrs [default: $($params.CPUCores)] (press `"Return`" to default)" -range @(1, (Get-CimInstance Win32_ComputerSystem).NumberOfLogicalProcessors) -AllowNull + $null = Get-VMParam -VMParam $VMParam + + $switch = Get-HyperVSwitchAdapter + $null = Set-CorrectHyperVSwitchAdapterDialog -Name $switch + + $null = Get-VMGpuPartitionAdapterFriendlyName + $null = Get-GPUDedicatedResourcePercentage + + Write-Host "Guest OS Parameters:" -ForegroundColor Yellow + $null = Open-ISOImageDialog + $params.DriveLetter = Mount-ISOReliable -SourcePath $params.SourcePath + + $Editions = Get-ISOWindowsEditions -DriveLetter $params.DriveLetter + if ($null -ne $Editions) { + $VMParam = New-VMParameter -name 'Edition' -title "Select Index of the Windows Edition [default: $($Editions.Count)] (press `"Return`" to skip)" -range @(1, $Editions.Count) -AllowNull $true + $null = Get-VMParam -VMParam $VMParam + } else { + $param.Edition = 0 + } + + $null = Get-GuestOSCredentials + + $VMParam = New-VMParameter -name 'Autologon' -title "Enable Autologon to Guest OS? [Y/N] [default: $(BoolToYesNo $params.Autologon)] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + $null = Get-VMParam -VMParam $VMParam + + $VMParam = New-VMParameter -name 'CopyRegionalSettings' -title "Copy Host OS regional settings (locale, keyboard layout etc.) to Guest OS? [Y/N] [default: Y] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + $null = Get-VMParam -VMParam $VMParam + + $VMParam = New-VMParameter -name 'NumLock' -title "Enable NumLock at Logon? [Y/N] [default: $(BoolToYesNo $params.NumLock)] (press `"Return`" to enable)" -AllowedValues @{Y = $true; N = $false} -AllowNull + $null = Get-VMParam -VMParam $VMParam + + Get-RemoteDesktopApp + if ($params.Parsec -eq $true) { + $VMParam = New-VMParameter -name 'ParsecVDD' -title "Install Parsec Virtual Display Driver? [Y/N] [default: $(BoolToYesNo $params.ParsecVDD)] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + if ((Get-VMParam -VMParam $VMParam) -eq $true) { + $VMParam = New-VMParameter -name 'DisableHVDD' -title "Disable Hyper-V Display Driver? [Y/N] [default: $(BoolToYesNo $params.DisableHVDD)] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + $null = Get-VMParam -VMParam $VMParam + } + $VMParam = New-VMParameter -name 'ParsecForTeamsSubscriber' -title "Are you are a Parsec for Teams Subscriber? [Y/N] [default: N] (press `"Return`" to skip)" -AllowedValues @{Y = $true; N = $false} -AllowNull + if ((Get-VMParam -VMParam $VMParam) -eq 0) { + $VMParam = New-VMParameter -name 'Team_ID' -title "Enter the Parsec for Teams ID (press `"Return`" to skip)" -AllowNull + $null = Get-VMParam -VMParam $VMParam + + $VMParam = New-VMParameter -name 'Key' -title "Enter the Parsec for Teams Secret Key (press `"Return`" to skip)" -AllowNull + $null = Get-VMParam -VMParam $VMParam + } + } +} +#======================================================================== + +#======================================================================== +function Start-VMandConnect { + param([string]$Name) + Start-VM -Name $Name + Start-Sleep -s 5 + If ((Get-Process VMconnect -ErrorAction SilentlyContinue).Length -eq 0) { + VMconnect $env:COMPUTERNAME $Name + } +} +#======================================================================== + +#======================================================================== +#Script executing section +Clear-Host +Write-Host "System is checking ..." -ForegroundColor Yellow + +If ((Is-Administrator) -and (Get-WindowsCompatibleOS) -and (Get-HyperVEnabled)) { + Write-Host "Checking completed: " -NoNewline -ForegroundColor Yellow + Write-Host "System is Compatible" -ForegroundColor DarkGreen + + $Action = Get-Action + Write-Host "`r`nRequired parameters:" -ForegroundColor Yellow + + switch ($Action) { + 1 { Get-VMParams + New-GPUEnabledVM @params } + 2 { Get-VMObjects + $null = Get-VMGpuPartitionAdapterFriendlyName + Get-GPUDedicatedResourcePercentage + Delete-VMGPUPartitionAdapter + Pass-VMGPUPartitionAdapter + Copy-GPUDrivers } + 3 { Get-VMObjects + if ((Get-VMGpuPartitionAdapterFriendlyName -GetPassedGPU) -eq $true) { + Get-GPUDedicatedResourcePercentage + Pass-VMGPUPartitionAdapter + } + Copy-GPUDrivers } + 4 { Get-VMObjects + Delete-VMGPUPartitionAdapter } + 5 { Get-VMObjects + Pass-VMGPUPartitionAdapter -OnlyResources } + } + + if ($Global:ServerOS -eq $true) { + Set-ServerOSGroupPolicies + } + + If ($Global:StateWasRunning){ + Write-Host "Previous State was running so starting VM..." + Start-VMandConnect -Name $Global:VM.Name + } + + if ($Action -eq 1) { + Start-VMandConnect -Name $params.VMName + $m = "If all went well the Virtual Machine will have started, + `rIn a few minutes it will load the Windows desktop." + if (($params.Parsec -eq $true) -and ($params.RDP -eq $false)) { + $m += "When it does, sign into Parsec (a fast remote desktop app) + `rand connect to the machine using Parsec from another computer. + `rHave fun! + `rSign up to Parsec at https://Parsec.app" + } elseif (($params.Parsec -eq $false) -and ($params.RDP -eq $true)) { + $m += "When it does, install Microsot Remote Desktop moder client + `rand connect to the machine using username and password you set. + `rHave fun! + `rhttps://www.microsoft.com/store/productId/9WZDNCRFJ3PS" + } elseif (($params.Parsec -eq $true) -and ($params.RDP -eq $true)) { + $m += "When it does, sign into Parsec (a fast remote desktop app) + `rand connect to the machine using Parsec from another computer. + `ror install Microsot Remote Desktop moder client + `rand connect to the machine using username and password you set. + `rHave fun! + `rSign up to Parsec at https://Parsec.app + `rhttps://www.microsoft.com/store/productId/9WZDNCRFJ3PS" + } + } else { + $m = "Done..." + } + SmartExit -ExitReason $m +} +#======================================================================== diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/Machine/Install.ps1 b/Machine/Install.ps1 deleted file mode 100644 index 946fe6d..0000000 --- a/Machine/Install.ps1 +++ /dev/null @@ -1,33 +0,0 @@ -<# -if (!(Test-Path C:\ProgramData\Easy-GPU-P\second.txt)) { - exit - } -else { - if( !((Get-ChildItem -Path Cert:\CurrentUser\TrustedPublisher).DnsNameList.Unicode -like "Parsec Cloud, Inc.")) { - $Success = $false - [int]$Retries = 0 - do { - try { - Import-Certificate -CertStoreLocation Cert:\CurrentUser\TrustedPublisher -FilePath C:\ProgramData\Easy-GPU-P\parsecpublic.cer - $Success = $true - } - catch { - if ($Retries -gt 60){ - $Success = $true - } - else { - Start-Sleep -Seconds 1 - $Error[0] |Out-File C:\ProgramData\Easy-GPU-P\log.txt - $env:USERNAME | Out-File C:\ProgramData\Easy-GPU-P\username.txt - $Retries++ - - } - } - } - While ($Success -eq $false) - - } - Else { - } - } -#> \ No newline at end of file diff --git a/Machine/psscripts.ini b/Machine/psscripts.ini deleted file mode 100644 index 7b4cd05..0000000 --- a/Machine/psscripts.ini +++ /dev/null @@ -1,4 +0,0 @@ - -[Startup] -0CmdLine=Install.ps1 -0Parameters= \ No newline at end of file diff --git a/PreChecks.ps1 b/PreChecks.ps1 deleted file mode 100644 index fe8a611..0000000 --- a/PreChecks.ps1 +++ /dev/null @@ -1,65 +0,0 @@ - - -Function Get-DesktopPC -{ - $isDesktop = $true - if(Get-WmiObject -Class win32_systemenclosure | Where-Object { $_.chassistypes -eq 9 -or $_.chassistypes -eq 10 -or $_.chassistypes -eq 14}) - { - Write-Warning "Computer is a laptop. Laptop dedicated GPU's that are partitioned and assigned to VM may not work with Parsec." - Write-Warning "Thunderbolt 3 or 4 dock based GPU's may work" - $isDesktop = $false } - if (Get-WmiObject -Class win32_battery) - { $isDesktop = $false } - $isDesktop -} - -Function Get-WindowsCompatibleOS { -$build = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -if ($build.CurrentBuild -ge 19041 -and ($($build.editionid -like 'Professional*') -or $($build.editionid -like 'Enterprise*') -or $($build.editionid -like 'Education*'))) { - Return $true - } -Else { - Write-Warning "Only Windows 10 20H1 or Windows 11 (Pro or Enterprise) is supported" - Return $false - } -} - - -Function Get-HyperVEnabled { -if (Get-WindowsOptionalFeature -Online | Where-Object FeatureName -Like 'Microsoft-Hyper-V-All'){ - Return $true - } -Else { - Write-Warning "You need to enable Virtualisation in your motherboard and then add the Hyper-V Windows Feature and reboot" - Return $false - } -} - -Function Get-WSLEnabled { - if ((wsl -l -v)[2].length -gt 1 ) { - Write-Warning "WSL is Enabled. This may interferre with GPU-P and produce an error 43 in the VM" - Return $true - } - Else { - Return $false - } -} - -Function Get-VMGpuPartitionAdapterFriendlyName { - $Devices = (Get-WmiObject -Class "Msvm_PartitionableGpu" -ComputerName $env:COMPUTERNAME -Namespace "ROOT\virtualization\v2").name - Foreach ($GPU in $Devices) { - $GPUParse = $GPU.Split('#')[1] - Get-WmiObject Win32_PNPSignedDriver | where {($_.HardwareID -eq "PCI\$GPUParse")} | select DeviceName -ExpandProperty DeviceName - } -} - -If ((Get-DesktopPC) -and (Get-WindowsCompatibleOS) -and (Get-HyperVEnabled)) { -"System Compatible" -"Printing a list of compatible GPUs...May take a second" -"Copy the name of the GPU you want to share..." -Get-VMGpuPartitionAdapterFriendlyName -Read-Host -Prompt "Press Enter to Exit" -} -else { -Read-Host -Prompt "Press Enter to Exit" -} diff --git a/README.md b/README.md index 5bb9f9a..5a6331e 100644 --- a/README.md +++ b/README.md @@ -1,69 +1,52 @@ -# Easy-GPU-PV -A work-in-progress project dedicated to making GPU Paravirtualization on Windows Hyper-V easier! +# Interactive-Easy-GPU-PV +A work-in-progress fork of [jamesstringerparse Easy-GPU-PV repository](https://github.com/jamesstringerparsec/Easy-GPU-PV). The goal of the project is to simplify the entire process as much as possible. The main script is interactive, so users don't have to define any parameters in advance. Instead, parameters can be chosen while the script is running, making the process much easier. + +![Administrator_-PowerShell-2023-03-21-16-38-00](https://user-images.githubusercontent.com/77991615/226651194-032db39b-291a-4cd4-a231-da5a215c9eee.gif) + +***The following text is primarily taken from the original Easy-GPU-PV project. I've made some modifications and improvements to ensure that it accurately reflects the current state of the project and provides relevant information.*** GPU-PV allows you to partition your systems dedicated or integrated GPU and assign it to several Hyper-V VMs. It's the same technology that is used in WSL2, and Windows Sandbox. -Easy-GPU-PV aims to make this easier by automating the steps required to get a GPU-PV VM up and running. -Easy-GPU-PV does the following... +Interactive-Easy-GPU-PV aims to make this easier by automating the steps required to get a GPU-PV VM up and running. +This project provides the following... 1) Creates a VM of your choosing 2) Automatically Installs Windows to the VM 3) Partitions your GPU of choice and copies the required driver files to the VM 4) Installs [Parsec](https://parsec.app) to the VM, Parsec is an ultra low latency remote desktop app, use this to connect to the VM. You can use Parsec for free non commercially. To use Parsec commercially, sign up to a [Parsec For Teams](https://parsec.app/teams) account +5) Configures Microsoft Remote Desktop to provide 3D accelerated remote session. Note that 3D acceleration during a Microsoft RDP remote session isn't that perfomance as Parsec Remote Desktop session is. ### Prerequisites: -* Windows 10 20H1+ Pro, Enterprise or Education OR Windows 11 Pro, Enterprise or Education. Windows 11 on host and VM is preferred due to better compatibility. -* Matched Windows versions between the host and VM. Mismatches may cause compatibility issues, blue-screens, or other issues. (Win10 21H1 + Win10 21H1, or Win11 21H2 + Win11 21H2, for example) -* Desktop Computer with dedicated NVIDIA/AMD GPU or Integrated Intel GPU - Laptops with NVIDIA GPUs are not supported at this time, but Intel integrated GPUs work on laptops. GPU must support hardware video encoding (NVIDIA NVENC, Intel Quicksync or AMD AMF). -* Latest GPU driver from Intel.com or NVIDIA.com, don't rely on Device manager or Windows update. +* A desktop computer running Windows 10 20H1+ Pro, Enterprise, or Education, or Windows 11 Pro, Enterprise, or Education, or Windows Server 2022. Windows 11 or Windows Server 2022 is preferred for better compatibility. The host and VM must have matching Windows versions, as mismatches can cause compatibility issues, blue-screens, or other problems. For example, Win10 21H1 + Win10 21H1 or Win11 21H2 + Win11 21H2. +* PC with dedicated NVIDIA/AMD GPU or integrated Intel GPU. Laptops with NVIDIA GPUs are currently not supported, but Intel integrated GPUs work on laptops. The GPU must support hardware video encoding (NVIDIA NVENC, Intel Quicksync, or AMD AMF). +* The latest GPU driver from [Intel.com](https://www.intel.com/content/www/us/en/search.html#sort=relevancy&f:@tabfilter=[Downloads]&f:@stm_10385_en=[Graphics]) or [AMD.com](https://www.amd.com/en/support) or [NVIDIA.com](https://www.nvidia.com/download/index.aspx) (for desktop NVIDIA GPUs, only the GameReady driver is supported). Do not rely on Device Manager or Windows Update to install the driver. It's important to ensure that you have the latest driver installed to avoid compatibility issues and ensure optimal performance. * Latest Windows 10 ISO [downloaded from here](https://www.microsoft.com/en-gb/software-download/windows10ISO) / Windows 11 ISO [downloaded from here.](https://www.microsoft.com/en-us/software-download/windows11) - Do not use Media Creation Tool, if no direct ISO link is available, follow [this guide.](https://www.nextofwindows.com/downloading-windows-10-iso-images-using-rufus) * Virtualisation enabled in the motherboard and [Hyper-V fully enabled](https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v) on the Windows 10/ 11 OS (requires reboot). * Allow Powershell scripts to run on your system - typically by running "Set-ExecutionPolicy unrestricted" in Powershell running as Administrator. ### Instructions -1. Make sure your system meets the prerequisites. -2. [Download the Repo and extract.](https://github.com/jamesstringerparsec/Easy-GPU-PV/archive/refs/heads/main.zip) -3. Search your system for Powershell ISE and run as Administrator. -4. In the extracted folder you downloaded, open PreChecks.ps1 in Powershell ISE. Run the files from within the extracted folder. Do not move them. -5. Open and Run PreChecks.ps1 in Powershell ISE using the green play button and copy the GPU Listed (or the warnings that you need to fix). -6. Open CopyFilesToVM.ps1 Powershell ISE and edit the params section at the top of the file, you need to be careful about how much ram, storage and hard drive you give it as your system needs to have that available. On Windows 10 the GPUName must be left as "AUTO", In Windows 11 it can be either "AUTO" or the specific name of the GPU you want to partition exactly how it appears in PreChecks.ps1. Additionally, you need to provide the path to the Windows 10/11 ISO file you downloaded. -7. Run CopyFilesToVM.ps1 with your changes to the params section - this may take 5-10 minutes. -8. Open and sign into Parsec on the VM. You can use Parsec to connect to the VM up to 4K60FPS. -9. You should be good to go! - -### Upgrading GPU Drivers when you update the host GPU Drivers -It's important to update the VM GPU Drivers after you have updated the Host GPUs drivers. You can do this by... -1. Reboot the host after updating GPU Drivers. -2. Open Powershell as administrator and change directory (CD) to the path that CopyFilesToVM.ps1 and Update-VMGpuPartitionDriver.ps1 are located. -3. Run ```Update-VMGpuPartitionDriver.ps1 -VMName "Name of your VM" -GPUName "Name of your GPU"``` (Windows 10 GPU name must be "AUTO") +To get started with Interactive-Easy-GPU-PV, follow these steps: +1) Make sure your system meets all the prerequisites mentioned in the documentation. +2) Download the [Interactive-Easy-GPU-PV repository](https://github.com/jamesstringerparsec/Easy-GPU-PV/archive/refs/heads/main.zip) and extract it to a folder on your computer. You can download it from the project's GitHub page. +3) Search for Powershell ISE on your computer and run it as Administrator. +4) Navigate to the extracted folder you downloaded and run the interactive script named "GPUP-management.ps1". Select "Create new VM with GPU acceleration" when prompted and set any required parameters. The script will start creating the VM, which may take 5-10 minutes depending on your system. +5) Once the VM is created, open and sign into Parsec on the VM. You can use Parsec to connect to the VM at up to 4K60FPS. +6) You're all set, enjoy! -### Values - ```VMName = "GPUP"``` - Name of VM in Hyper-V and the computername / hostname - ```SourcePath = "C:\Users\james\Downloads\Win11_English_x64.iso"``` - path to Windows 10/ 11 ISO on your host - ```Edition = 6``` - Leave as 6, this means Windows 10/11 Pro - ```VhdFormat = "VHDX"``` - Leave this value alone - ```DiskLayout = "UEFI"``` - Leave this value alone - ```SizeBytes = 40gb``` - Disk size, in this case 40GB, the minimum is 20GB - ```MemoryAmount = 8GB``` - Memory size, in this case 8GB - ```CPUCores = 4``` - CPU Cores you want to give VM, in this case 4 - ```NetworkSwitch = "Default Switch"``` - Leave this alone unless you're not using the default Hyper-V Switch - ```VHDPath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\"``` - Path to the folder you want the VM Disk to be stored in, it must already exist - ```UnattendPath = "$PSScriptRoot"+"\autounattend.xml"``` -Leave this value alone - ```GPUName = "AUTO"``` - AUTO selects the first available GPU. On Windows 11 you may also use the exact name of the GPU you want to share with the VM in multi GPU situations (GPU selection is not available in Windows 10 and must be set to AUTO) - ```GPUResourceAllocationPercentage = 50``` - Percentage of the GPU you want to share with the VM - ```Team_ID = ""``` - The Parsec for Teams ID if you are a Parsec for Teams Subscriber - ```Key = ""``` - The Parsec for Teams Secret Key if you are a Parsec for Teams Subscriber - ```Username = "GPUVM"``` - The VM Windows Username, do not include special characters, and must be different from the "VMName" value you set - ```Password = "CoolestPassword!"``` - The VM Windows Password, cannot be blank - ```Autologon = "true"```- If you want the VM to automatically login to the Windows Desktop +### Upgrading VM GPU Drivers after you update the host GPU Drivers +To ensure proper functioning of the VM, it's important to update the GPU drivers inside the VM after updating the drivers on the host machine. To do this, follow these steps: +1) After updating the GPU drivers on the host machine, reboot it. +2) Open Powershell as an administrator, navigate to the extracted folder of the Interactive-Easy-GPU-PV repo and run the interactive script GPUP-management.ps1. +3) Select action 3: Copy GPU Drivers from Host to VM. This will copy the updated GPU drivers from the host machine to the VM. ### Thanks to: +- [jamesstringerparsec](https://github.com/jamesstringerparsec/Easy-GPU-PV) for creating EASY-GPU-PV project that was taken as a base as well as main part of this readme - [Hyper-ConvertImage](https://github.com/tabs-not-spaces/Hyper-ConvertImage) for creating an updated version of [Convert-WindowsImage](https://github.com/MicrosoftDocs/Virtualization-Documentation/tree/master/hyperv-tools/Convert-WindowsImage) that is compatible with Windows 10 and 11. -- [gawainXX](https://github.com/gawainXX) for help testing and pointing out bugs and feature improvements. +- [gawainXX](https://github.com/gawainXX) for help [jamesstringerparsec](https://github.com/jamesstringerparsec/Easy-GPU-PV) testing and pointing out bugs and feature improvements. ### Notes: -- After you have signed into Parsec on the VM, always use Parsec to connect to the VM. Keep the Microsft Hyper-V Video adapter disabled. Using RDP and Hyper-V Enhanced Session mode will result in broken behaviour and black screens in Parsec. RDP and the Hyper-V video adapter only offer a maximum of 30FPS. Using Parsec will allow you to use up to 4k60 FPS. +- If you install Parsec Virtual Display Driver (Parsec VDD), after you have signed into Parsec on the VM, always use Parsec to connect to the VM. Keep the Microsft Hyper-V Video adapter disabled. Using RDP and Hyper-V Enhanced Session mode will result in broken behaviour and black screens in Parsec. Using Parsec will allow you to use up to 4k60 FPS. - If you get "ERROR : Cannot bind argument to parameter 'Path' because it is null." this probably means you used Media Creation Tool to download the ISO. You unfortunately cannot use that, if you don't see a direct ISO download link at the Microsoft page, follow [this guide.](https://www.nextofwindows.com/downloading-windows-10-iso-images-using-rufus) - Your GPU on the host will have a Microsoft driver in device manager, rather than an nvidia/intel/amd driver. As long as it doesn't have a yellow triangle over top of the device in device manager, it's working correctly. - A powered on display / HDMI dummy dongle must be plugged into the GPU to allow Parsec to capture the screen. You only need one of these per host machine regardless of number of VM's. @@ -73,3 +56,4 @@ It's important to update the VM GPU Drivers after you have updated the Host GPUs - If you do not have administrator permissions on the machine it means you set the username and vmname to the same thing, these needs to be different. - AMD Polaris GPUS like the RX 580 do not support hardware video encoding via GPU Paravirtualization at this time. - To download Windows ISOs with Rufus, it must have "Check for updates" enabled. +Dd acceleration with Parsec VDD diff --git a/Update-VMGpuPartitionDriver.ps1 b/Update-VMGpuPartitionDriver.ps1 deleted file mode 100644 index 157b22b..0000000 --- a/Update-VMGpuPartitionDriver.ps1 +++ /dev/null @@ -1,52 +0,0 @@ -<# -If you are opening this file in Powershell ISE you should modify the params section like so... -Remember: GPU Name must match the name of the GPU you assigned when creating the VM... - -Param ( -[string]$VMName = "NameofyourVM", -[string]$GPUName = "NameofyourGPU", -[string]$Hostname = $ENV:Computername -) - -#> - -Param ( -[string]$VMName, -[string]$GPUName, -[string]$Hostname = $ENV:Computername -) - -Import-Module $PSSCriptRoot\Add-VMGpuPartitionAdapterFiles.psm1 - -$VM = Get-VM -VMName $VMName -$VHD = Get-VHD -VMId $VM.VMId - -If ($VM.state -eq "Running") { - [bool]$state_was_running = $true - } - -if ($VM.state -ne "Off"){ - "Attemping to shutdown VM..." - Stop-VM -Name $VMName -Force - } - -While ($VM.State -ne "Off") { - Start-Sleep -s 3 - "Waiting for VM to shutdown - make sure there are no unsaved documents..." - } - -"Mounting Drive..." -$DriveLetter = (Mount-VHD -Path $VHD.Path -PassThru | Get-Disk | Get-Partition | Get-Volume | Where-Object {$_.DriveLetter} | ForEach-Object DriveLetter) - -"Copying GPU Files - this could take a while..." -Add-VMGPUPartitionAdapterFiles -hostname $Hostname -DriveLetter $DriveLetter -GPUName $GPUName - -"Dismounting Drive..." -Dismount-VHD -Path $VHD.Path - -If ($state_was_running){ - "Previous State was running so starting VM..." - Start-VM $VMName - } - -"Done..." \ No newline at end of file diff --git a/User/Install.ps1 b/User/Install.ps1 deleted file mode 100644 index bdc007f..0000000 --- a/User/Install.ps1 +++ /dev/null @@ -1,212 +0,0 @@ -param( -$team_id, -$key -) - -while(!(Test-NetConnection Google.com).PingSucceeded){ - Start-Sleep -Seconds 1 - } - -Get-ChildItem -Path C:\ProgramData\Easy-GPU-P -Recurse | Unblock-File - -if (Test-Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Parsec) - {} - else { - (New-Object System.Net.WebClient).DownloadFile("https://builds.parsecgaming.com/package/parsec-windows.exe", "C:\Users\$env:USERNAME\Downloads\parsec-windows.exe") - Start-Process "C:\Users\$env:USERNAME\Downloads\parsec-windows.exe" -ArgumentList "/silent", "/shared","/team_id=$team_id","/team_computer_key=$key" -wait - While (!(Test-Path C:\ProgramData\Parsec\config.txt)){ - Start-Sleep -s 1 - } - $configfile = Get-Content C:\ProgramData\Parsec\config.txt - $configfile += "host_virtual_monitors = 1" - $configfile += "host_privacy_mode = 1" - $configfile | Out-File C:\ProgramData\Parsec\config.txt -Encoding ascii - Copy-Item -Path "C:\ProgramData\Easy-GPU-P\Parsec.lnk" -Destination "C:\Users\Public\Desktop" - Stop-Process parsecd -Force - } - -Function ParsecVDDMonitorSetupScheduledTask { -$XML = @" -<?xml version="1.0" encoding="UTF-16"?> -<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> - <RegistrationInfo> - <Description>Monitors the state of Parsec Virtual Display and repairs if broken</Description> - <URI>\Monitor Parsec VDD State</URI> - </RegistrationInfo> - <Triggers> - <LogonTrigger> - <Enabled>true</Enabled> - <UserId>$(([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name)</UserId> - <Delay>PT2M</Delay> - </LogonTrigger> - </Triggers> - <Principals> - <Principal id="Author"> - <UserId>$(([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value)</UserId> - <LogonType>S4U</LogonType> - <RunLevel>HighestAvailable</RunLevel> - </Principal> - </Principals> - <Settings> - <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> - <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> - <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> - <AllowHardTerminate>true</AllowHardTerminate> - <StartWhenAvailable>false</StartWhenAvailable> - <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> - <IdleSettings> - <StopOnIdleEnd>true</StopOnIdleEnd> - <RestartOnIdle>false</RestartOnIdle> - </IdleSettings> - <AllowStartOnDemand>true</AllowStartOnDemand> - <Enabled>true</Enabled> - <Hidden>false</Hidden> - <RunOnlyIfIdle>false</RunOnlyIfIdle> - <WakeToRun>false</WakeToRun> - <ExecutionTimeLimit>PT72H</ExecutionTimeLimit> - <Priority>7</Priority> - </Settings> - <Actions Context="Author"> - <Exec> - <Command>C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe</Command> - <Arguments>-file %programdata%\Easy-GPU-P\VDDMonitor.ps1</Arguments> - </Exec> - </Actions> -</Task> -"@ - - try { - Get-ScheduledTask -TaskName "Monitor Parsec VDD State" -ErrorAction Stop | Out-Null - Unregister-ScheduledTask -TaskName "Monitor Parsec VDD State" -Confirm:$false - } - catch {} - $action = New-ScheduledTaskAction -Execute 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument '-file %programdata%\Easy-GPU-P\VDDMonitor.ps1' - $trigger = New-ScheduledTaskTrigger -AtStartup - Register-ScheduledTask -XML $XML -TaskName "Monitor Parsec VDD State" | Out-Null - } -Function VBCableInstallSetupScheduledTask { -$XML = @" -<?xml version="1.0" encoding="UTF-16"?> -<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> - <RegistrationInfo> - <Description>Install VB Cable</Description> - <URI>\Install VB Cable</URI> - </RegistrationInfo> - <Triggers> - <LogonTrigger> - <Enabled>true</Enabled> - <UserId>$(([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name)</UserId> - <Delay>PT2M</Delay> - </LogonTrigger> - </Triggers> - <Principals> - <Principal id="Author"> - <UserId>$(([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value)</UserId> - <LogonType>S4U</LogonType> - <RunLevel>HighestAvailable</RunLevel> - </Principal> - </Principals> - <Settings> - <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> - <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> - <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> - <AllowHardTerminate>true</AllowHardTerminate> - <StartWhenAvailable>false</StartWhenAvailable> - <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> - <IdleSettings> - <StopOnIdleEnd>true</StopOnIdleEnd> - <RestartOnIdle>false</RestartOnIdle> - </IdleSettings> - <AllowStartOnDemand>true</AllowStartOnDemand> - <Enabled>true</Enabled> - <Hidden>false</Hidden> - <RunOnlyIfIdle>false</RunOnlyIfIdle> - <WakeToRun>false</WakeToRun> - <ExecutionTimeLimit>PT72H</ExecutionTimeLimit> - <Priority>7</Priority> - </Settings> - <Actions Context="Author"> - <Exec> - <Command>C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe</Command> - <Arguments>-file %programdata%\Easy-GPU-P\VBCableInstall.ps1</Arguments> - </Exec> - </Actions> -</Task> -"@ - - try { - Get-ScheduledTask -TaskName "Install VB Cable" -ErrorAction Stop | Out-Null - Unregister-ScheduledTask -TaskName "Install VB Cable" -Confirm:$false - } - catch {} - $action = New-ScheduledTaskAction -Execute 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument '-file %programdata%\Easy-GPU-P\VBCableInstall.ps1' - $trigger = New-ScheduledTaskTrigger -AtStartup - Register-ScheduledTask -XML $XML -TaskName "Install VB Cable" | Out-Null - } -Function ParsecVDDInstallSetupScheduledTask { -$XML = @" -<?xml version="1.0" encoding="UTF-16"?> -<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> - <RegistrationInfo> - <Description>Install Parsec Virtual Display Driver</Description> - <URI>\Install Parsec Virtual Display Driver</URI> - </RegistrationInfo> - <Triggers> - <LogonTrigger> - <Enabled>true</Enabled> - <UserId>$(([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name)</UserId> - <Delay>PT2M</Delay> - </LogonTrigger> - </Triggers> - <Principals> - <Principal id="Author"> - <UserId>$(([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value)</UserId> - <LogonType>S4U</LogonType> - <RunLevel>HighestAvailable</RunLevel> - </Principal> - </Principals> - <Settings> - <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> - <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> - <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> - <AllowHardTerminate>true</AllowHardTerminate> - <StartWhenAvailable>false</StartWhenAvailable> - <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> - <IdleSettings> - <StopOnIdleEnd>true</StopOnIdleEnd> - <RestartOnIdle>false</RestartOnIdle> - </IdleSettings> - <AllowStartOnDemand>true</AllowStartOnDemand> - <Enabled>true</Enabled> - <Hidden>false</Hidden> - <RunOnlyIfIdle>false</RunOnlyIfIdle> - <WakeToRun>false</WakeToRun> - <ExecutionTimeLimit>PT72H</ExecutionTimeLimit> - <Priority>7</Priority> - </Settings> - <Actions Context="Author"> - <Exec> - <Command>C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe</Command> - <Arguments>-file %programdata%\Easy-GPU-P\ParsecVDDInstall.ps1</Arguments> - </Exec> - </Actions> -</Task> -"@ - - try { - Get-ScheduledTask -TaskName "Install Parsec Virtual Display Driver" -ErrorAction Stop | Out-Null - Unregister-ScheduledTask -TaskName "Install Parsec Virtual Display Driver" -Confirm:$false - } - catch {} - $action = New-ScheduledTaskAction -Execute 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe' -Argument '-file %programdata%\Easy-GPU-P\ParsecVDDInstall.ps1' - $trigger = New-ScheduledTaskTrigger -AtStartup - Register-ScheduledTask -XML $XML -TaskName "Install Parsec Virtual Display Driver" | Out-Null - } - -ParsecVDDMonitorSetupScheduledTask -VBCableInstallSetupScheduledTask -ParsecVDDInstallSetupScheduledTask - -Start-ScheduledTask -TaskName "Install VB Cable" -Start-ScheduledTask -TaskName "Install Parsec Virtual Display Driver" -Start-ScheduledTask -TaskName "Monitor Parsec VDD State" \ No newline at end of file diff --git a/User/psscripts.ini b/User/psscripts.ini deleted file mode 100644 index 9292f3c..0000000 --- a/User/psscripts.ini +++ /dev/null @@ -1,4 +0,0 @@ - -[Logon] -0CmdLine=Install.ps1 -0Parameters= \ No newline at end of file diff --git a/VMScripts/Install.ps1 b/VMScripts/Install.ps1 new file mode 100644 index 0000000..0f6560e --- /dev/null +++ b/VMScripts/Install.ps1 @@ -0,0 +1,265 @@ +#======================================================================== +param( + $rdp, + $Parsec, + $ParsecVDD, + $DisableHVDD, + $NumLock, + $team_id, + $key +) +#======================================================================== + +#======================================================================== +function Remove-File { + param([Parameter(Mandatory = $true)][string]$Path) + if (Test-Path $Path) { Remove-Item $Path -Force } +} +#======================================================================== + +#======================================================================== +Remove-File "C:\unattend.xml" +Remove-File "C:\Windows\system32\GroupPolicy\User\Scripts\psscripts.ini" +Remove-File "C:\Windows\system32\GroupPolicy\User\Scripts\Logon\Install.ps1" + +if ($NumLock -eq $true) { + $WshShell = New-Object -ComObject WScript.Shell + for ($i=0; $i -lt 5; $i++) { + Start-Sleep -s 0.1 + if ([console]::NumberLock -eq $false) { + $WshShell.SendKeys("{NUMLOCK}") + } else { break } + } + $path = "$DriveLetter\Windows\system32\GroupPolicy\User\Scripts\psscripts.ini" + "[Logon]" >> $path + "0CmdLine=NumLockEnable.ps1" >> $path + "0Parameters=" >> $path + + $path = "$DriveLetter\Windows\system32\GroupPolicy\User\Scripts\Logon\NumLockEnable.ps1" + "`$WshShell = New-Object -ComObject WScript.Shell" >> $path + "for (`$i=0; `$i -lt 5; `$i++) {" >> $path + " Start-Sleep -s 0.1" >> $path + " if ([console]::NumberLock -eq `$false) {" >> $path + " `$WshShell.SendKeys(`"{NUMLOCK}`")" >> $path + " } else { break }" >> $path + "}" >> $path +} +#======================================================================== + +#======================================================================== +function Set-RegistryPolicyItem { + param( + [Parameter(Mandatory = $true)] + [string] + [ValidateNotNullOrEmpty()]$path, + [Parameter(Mandatory = $true)] + [string] + [ValidateNotNullOrEmpty()]$name, + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()]$value, + [int]$type, + [switch]$Force + ) + + $RegPolPath = "$env:SystemRoot\System32\GroupPolicy\Machine\Registry.pol" + + if ($type -eq 0) { + $type = switch ($value.GetType().Fullname) { + 'System.String' { 1 } + 'System.Int32' { 4 } + 'System.Int64' { 11 } + default { return } + } + } + + function PolToUpperCase { + param( + [int[]]$data + ) + return $data | % -begin {$nameSection=$false} -process { + if ($_ -eq 91) { $nameSection = $true } + elseif($_ -eq 65) { $nameSection = $false } + elseif($_ -ge 97 -and $_ -le 122 -and $nameSection) { $_ -= 32 } + $_ + } + } + + function LastIndexOfBytesPattern { + param ( + [int[]]$data, + [int[]]$pattern + ) + $i, $j = 0, 0 + ForEach ($byte in $data) { + if($byte -eq $pattern[$j++]) { + if($j -eq $pattern.Count) { return $i } + } else { + $j = 0 + } + $i++ + } + return -1 + } + + if (Test-path -path $RegPolPath) { + $rawData = [io.file]::ReadAllBytes($RegPolPath) + } else { + $rawData = @(80, 82, 101, 103, 1, 0, 0, 0) + } + + $isUptoDate = $true + $keyData = [System.Text.Encoding]::Unicode.GetBytes($path) + $NameData = [System.Text.Encoding]::Unicode.GetBytes($name) + + switch ($true) { + ($type -eq 4 -or $type -eq 11) { $valueData = [BitConverter]::GetBytes($value) } + $default { $valueData = [System.Text.Encoding]::Unicode.GetBytes($value) } + } + + $pattern = @(91, 0) + $keyData + @(0, 0, 59, 0) + $NameData + @(0, 0, 59, 0) + $PolicyTypeOffset = (LastIndexOfBytesPattern (PolToUpperCase $rawData) (PolToUpperCase $pattern)) + 1 + + if ($PolicyTypeOffset -gt 0) { + $ValueOffset = 12 + $PolicyTypeOffset + if ($rawData[$PolicyTypeOffset] -ne $type) { + return + } + for ($i = 0; $i -lt $valueData.Count; $i++) { + if ($rawData[$i + $ValueOffset] -ne $valueData[$i]) { + $isUptoDate = $false + } + $rawData[$i + $ValueOffset] = $valueData[$i] + } + } else { + $isUptoDate = $false + $rawData += $pattern + @($type, 0, 0, 0, 59, 0, $type, 0, 0, 0, 59, 0) + $valueData + @(93, 0) + } + + if ($isUptoDate -eq $false) { + [io.file]::WriteAllBytes($RegPolPath, $rawData) + if ($Force -eq $true) { + Start-Process -FilePath "gpupdate" -ArgumentList "/force" -NoNewWindow -Wait + } + } +} +#======================================================================== + +#======================================================================== +function Set-AllowInBoundConnections { + param() + if ((Get-NetFirewallProfile -Profile Domain).DefaultInboundAction -ne 'Allow') { + Set-NetFirewallProfile -Profile Domain -DefaultInboundAction 'Allow' + } + if ((Get-NetFirewallProfile -Profile Private).DefaultInboundAction -ne 'Allow') { + Set-NetFirewallProfile -Profile Private -DefaultInboundAction 'Allow' + } + if ((Get-NetFirewallProfile -Profile Public).DefaultInboundAction -ne 'Allow') { + Set-NetFirewallProfile -Profile Public -DefaultInboundAction 'Allow' + } + Set-RegistryPolicyItem -Path "SOFTWARE\Policies\Microsoft\Windows Defender Security Center\Notifications" -Name "DisableNotifications" -Value 1 + Set-RegistryPolicyItem -Path "SOFTWARE\Policies\Microsoft\Windows Defender Security Center\Notifications" -Name "DisableEnhancedNotifications" -Value 1 + Set-RegistryPolicyItem -Path "SOFTWARE\Policies\Microsoft\Windows Defender Security Center\Firewall and network protection" -Name "UILockdown" -Value 1 + Set-RegistryPolicyItem -Path "Software\Policies\Microsoft\Windows NT\Terminal Services" -Name "ColorDepth" -Value 4 + Set-RegistryPolicyItem -Path "Software\Policies\Microsoft\Windows NT\Terminal Services" -Name "bEnumerateHWBeforeSW" -Value 1 + Set-RegistryPolicyItem -Path "Software\Policies\Microsoft\Windows NT\Terminal Services" -Name "fEnableVirtualizedGraphics" -Value 1 + Set-RegistryPolicyItem -Path "Software\Policies\Microsoft\Windows NT\Terminal Services" -Name "AVC444ModePreferred" -Value 1 + Set-RegistryPolicyItem -Path "Software\Policies\Microsoft\Windows NT\Terminal Services" -Name "fEnableWddmDriver" -Value 0 -Force +} +#======================================================================== + +#======================================================================== +function Install-VBCable { + param() + if (!(Get-WmiObject Win32_SoundDevice | Where-Object name -like "VB-Audio Virtual Cable")) { + (New-Object System.Net.WebClient).DownloadFile("https://download.vb-audio.com/Download_CABLE/VBCABLE_Driver_Pack43.zip", "C:\Users\$env:USERNAME\Downloads\VBCable.zip") + New-Item -Path "C:\Users\$env:Username\Downloads\VBCable" -ItemType Directory| Out-Null + Expand-Archive -Path "C:\Users\$env:USERNAME\Downloads\VBCable.zip" -DestinationPath "C:\Users\$env:USERNAME\Downloads\VBCable" + $pathToCatFile = "C:\Users\$env:USERNAME\Downloads\VBCable\vbaudio_cable64_win7.cat" + $FullCertificateExportPath = "C:\Users\$env:USERNAME\Downloads\VBCable\VBCert.cer" + $VB = @{} + $VB.DriverFile = $pathToCatFile; + $VB.CertName = $FullCertificateExportPath; + $VB.ExportType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert; + $VB.Cert = (Get-AuthenticodeSignature -filepath $VB.DriverFile).SignerCertificate; + [System.IO.File]::WriteAllBytes($VB.CertName, $VB.Cert.Export($VB.ExportType)) + while (((Get-ChildItem Cert:\LocalMachine\TrustedPublisher) | Where-Object {$_.Subject -like '*Vincent Burel*'}) -eq $NULL) { + certutil -Enterprise -Addstore "TrustedPublisher" $VB.CertName + Start-Sleep -s 5 + } + Start-Process -FilePath "C:\Users\$env:Username\Downloads\VBCable\VBCABLE_Setup_x64.exe" -ArgumentList '-i','-h' + } +} +#======================================================================== + +#======================================================================== +function Install-ParsecVDD { + param() + if (!(Get-WmiObject Win32_VideoController | Where-Object name -like "Parsec Virtual Display Adapter")) { + (New-Object System.Net.WebClient).DownloadFile("https://builds.Parsec.app/vdd/Parsec-vdd-0.41.0.0.exe", "C:\Users\$env:USERNAME\Downloads\Parsec-vdd.exe") + while (((Get-ChildItem Cert:\LocalMachine\TrustedPublisher) | Where-Object {$_.Subject -like '*Parsec*'}) -eq $NULL) { + certutil -Enterprise -Addstore "TrustedPublisher" C:\ProgramData\Easy-GPU-P\ParsecPublic.cer + Start-Sleep -s 5 + } + if ($DisableHVDD -eq $true) { + Get-PnpDevice | Where-Object {($_.Instanceid | Select-String -Pattern "VMBUS") -and $_.Class -like "Display" -and $_.status -eq "OK"} | Disable-PnpDevice -confirm:$false + } + Start-Process "C:\Users\$env:USERNAME\Downloads\Parsec-vdd.exe" -ArgumentList "/s" + } +} +#======================================================================== + +#======================================================================== +function Set-EasyGPUPScheduledTask { + param ( + [switch]$RunOnce, + [string]$TaskName, + [string]$Path + ) + if(!(Get-ScheduledTask | Where-Object { $_.TaskName -like "$($TaskName)" })) { + $principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest + $Action = New-ScheduledTaskAction -Execute "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-file $Path" + $Trigger = New-ScheduledTaskTrigger -AtStartup + New-ScheduledTask -Action $Action -Trigger $Trigger -Principal $principal | Register-ScheduledTask -TaskName "$TaskName" + } elseif ($RunOnce -eq $true) { + Unregister-ScheduledTask -TaskName "$TaskName" -Confirm:$false + } +} +#======================================================================== + +#======================================================================== +while(!(Test-NetConnection Google.com).PingSucceeded) { + Start-Sleep -Seconds 1 +} + +Get-ChildItem -Path C:\ProgramData\Easy-GPU-P -Recurse | Unblock-File + +if ($Parsec -eq $true) { + if ((Test-Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Parsec) -eq $false) { + (New-Object System.Net.WebClient).DownloadFile("https://builds.parsecgaming.com/package/parsec-windows.exe", "C:\Users\$env:USERNAME\Downloads\Parsec-windows.exe") + Start-Process "C:\Users\$env:USERNAME\Downloads\Parsec-windows.exe" -ArgumentList "/silent", "/shared","/team_id=$team_id","/team_computer_key=$key" -wait + while (!(Test-Path C:\ProgramData\Parsec\config.txt)) { + Start-Sleep -s 1 + } + $configfile = Get-Content C:\ProgramData\Parsec\config.txt + $configfile += "host_virtual_monitors = 1" + $configfile += "host_privacy_mode = 1" + $configfile | Out-File C:\ProgramData\Parsec\config.txt -Encoding ascii + Copy-Item -Path "C:\ProgramData\Easy-GPU-P\Parsec.lnk" -Destination "C:\Users\Public\Desktop" + try { + Stop-Process Parsecd -Force + } catch { + } + } + if ($ParsecVDD -eq $true) { + Install-ParsecVDD + } + Install-VBCable + if ($ParsecVDD -eq $true) { + Set-EasyGPUPScheduledTask -TaskName "Monitor Parsec VDD State" -Path "%programdata%\Easy-GPU-P\VDDMonitor.ps1" + } +} + +if ($rdp -eq $true) { + Set-AllowInBoundConnections +} +#======================================================================== diff --git a/VMScripts/Parsec.lnk b/VMScripts/Parsec.lnk deleted file mode 100644 index a31af00..0000000 Binary files a/VMScripts/Parsec.lnk and /dev/null differ diff --git a/VMScripts/ParsecVDDInstall.ps1 b/VMScripts/ParsecVDDInstall.ps1 deleted file mode 100644 index 3664fdc..0000000 --- a/VMScripts/ParsecVDDInstall.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -if (!(Get-WmiObject Win32_VideoController | Where-Object name -like "Parsec Virtual Display Adapter")) { -(New-Object System.Net.WebClient).DownloadFile("https://builds.parsec.app/vdd/parsec-vdd-0.41.0.0.exe", "C:\Users\$env:USERNAME\Downloads\parsec-vdd.exe") -while (((Get-ChildItem Cert:\LocalMachine\TrustedPublisher) | Where-Object {$_.Subject -like '*Parsec*'}) -eq $NULL) { - certutil -Enterprise -Addstore "TrustedPublisher" C:\ProgramData\Easy-GPU-P\ParsecPublic.cer - Start-Sleep -s 5 - } -Get-PnpDevice | Where-Object {$_.friendlyname -like "Microsoft Hyper-V Video" -and $_.status -eq "OK"} | Disable-PnpDevice -confirm:$false -Start-Process "C:\Users\$env:USERNAME\Downloads\parsec-vdd.exe" -ArgumentList "/s" -} - diff --git a/VMScripts/VBCableInstall.ps1 b/VMScripts/VBCableInstall.ps1 deleted file mode 100644 index 1c981a7..0000000 --- a/VMScripts/VBCableInstall.ps1 +++ /dev/null @@ -1,19 +0,0 @@ -if (!(Get-WmiObject Win32_SoundDevice | Where-Object name -like "VB-Audio Virtual Cable")) { - (New-Object System.Net.WebClient).DownloadFile("https://download.vb-audio.com/Download_CABLE/VBCABLE_Driver_Pack43.zip", "C:\Users\$env:USERNAME\Downloads\VBCable.zip") - New-Item -Path "C:\Users\$env:Username\Downloads\VBCable" -ItemType Directory| Out-Null - Expand-Archive -Path "C:\Users\$env:USERNAME\Downloads\VBCable.zip" -DestinationPath "C:\Users\$env:USERNAME\Downloads\VBCable" - $pathToCatFile = "C:\Users\$env:USERNAME\Downloads\VBCable\vbaudio_cable64_win7.cat" - $FullCertificateExportPath = "C:\Users\$env:USERNAME\Downloads\VBCable\VBCert.cer" - $VB = @{} - $VB.DriverFile = $pathToCatFile; - $VB.CertName = $FullCertificateExportPath; - $VB.ExportType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert; - $VB.Cert = (Get-AuthenticodeSignature -filepath $VB.DriverFile).SignerCertificate; - [System.IO.File]::WriteAllBytes($VB.CertName, $VB.Cert.Export($VB.ExportType)) - while (((Get-ChildItem Cert:\LocalMachine\TrustedPublisher) | Where-Object {$_.Subject -like '*Vincent Burel*'}) -eq $NULL) { - certutil -Enterprise -Addstore "TrustedPublisher" $VB.CertName - Start-Sleep -s 5 - } - Start-Process -FilePath "C:\Users\$env:Username\Downloads\VBCable\VBCABLE_Setup_x64.exe" -ArgumentList '-i','-h' - } - \ No newline at end of file diff --git a/VMScripts/VDDMonitor.ps1 b/VMScripts/VDDMonitor.ps1 index 5e0701c..201d117 100644 --- a/VMScripts/VDDMonitor.ps1 +++ b/VMScripts/VDDMonitor.ps1 @@ -1,19 +1,10 @@ -$Global:VDD - -Function GetVDDState { -$Global:VDD = Get-PnpDevice | where {$_.friendlyname -like "Parsec Virtual Display Adapter"} -} - -While (1 -gt 0) { - GetVDDSTate - If ($Global:VDD -eq $NULL){ - Exit - } - Do { - Enable-PnpDevice -InstanceId $Global:VDD.InstanceId -Confirm:$false - Start-Sleep -s 5 - GetVDDState - } - Until ($Global:VDD.Status -eq 'OK') - Start-Sleep -s 10 +#======================================================================== +While ($true) { + $VDD = Get-PnpDevice | where {$_.friendlyname -like "Parsec Virtual Display Adapter"} + if (($VDD -eq $NULL) -or ($VDD.Status -eq 'OK')){ + exit + } + Enable-PnpDevice -InstanceId $VDD.InstanceId -Confirm:$false + Start-Sleep -s 5 } +#======================================================================== \ No newline at end of file diff --git a/autounattend.xml b/autounattend.xml deleted file mode 100644 index 3665e20..0000000 --- a/autounattend.xml +++ /dev/null @@ -1,204 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<unattend xmlns="urn:schemas-microsoft-com:unattend"> - <settings pass="windowsPE"> - <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <SetupUILanguage> - <UILanguage>en-US</UILanguage> - </SetupUILanguage> - <InputLocale>0409:00000409</InputLocale> - <SystemLocale>en-US</SystemLocale> - <UILanguage>en-US</UILanguage> - <UILanguageFallback>en-US</UILanguageFallback> - <UserLocale>en-AU</UserLocale> - </component> - <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <DiskConfiguration> - <Disk wcm:action="add"> - <DiskID>0</DiskID> - <WillWipeDisk>true</WillWipeDisk> - <CreatePartitions> - <!-- Windows RE Tools partition --> - <CreatePartition wcm:action="add"> - <Order>1</Order> - <Type>Primary</Type> - <Size>300</Size> - </CreatePartition> - <!-- System partition (ESP) --> - <CreatePartition wcm:action="add"> - <Order>2</Order> - <Type>EFI</Type> - <Size>100</Size> - </CreatePartition> - <!-- Microsoft reserved partition (MSR) --> - <CreatePartition wcm:action="add"> - <Order>3</Order> - <Type>MSR</Type> - <Size>128</Size> - </CreatePartition> - <!-- Windows partition --> - <CreatePartition wcm:action="add"> - <Order>4</Order> - <Type>Primary</Type> - <Extend>true</Extend> - </CreatePartition> - </CreatePartitions> - <ModifyPartitions> - <!-- Windows RE Tools partition --> - <ModifyPartition wcm:action="add"> - <Order>1</Order> - <PartitionID>1</PartitionID> - <Label>WINRE</Label> - <Format>NTFS</Format> - <TypeID>DE94BBA4-06D1-4D40-A16A-BFD50179D6AC</TypeID> - </ModifyPartition> - <!-- System partition (ESP) --> - <ModifyPartition wcm:action="add"> - <Order>2</Order> - <PartitionID>2</PartitionID> - <Label>System</Label> - <Format>FAT32</Format> - </ModifyPartition> - <!-- MSR partition does not need to be modified --> - <ModifyPartition wcm:action="add"> - <Order>3</Order> - <PartitionID>3</PartitionID> - </ModifyPartition> - <!-- Windows partition --> - <ModifyPartition wcm:action="add"> - <Order>4</Order> - <PartitionID>4</PartitionID> - <Label>OS</Label> - <Letter>C</Letter> - <Format>NTFS</Format> - </ModifyPartition> - </ModifyPartitions> - </Disk> - </DiskConfiguration> - <ImageInstall> - <OSImage> - <InstallTo> - <DiskID>0</DiskID> - <PartitionID>4</PartitionID> - </InstallTo> - <InstallToAvailablePartition>false</InstallToAvailablePartition> - </OSImage> - </ImageInstall> - <UserData> - <ProductKey> - <!-- Do not uncomment the Key element if you are using trial ISOs --> - <!-- You must uncomment the Key element (and optionally insert your own key) if you are using retail or volume license ISOs --> - <Key> - </Key> - <WillShowUI>Never</WillShowUI> - </ProductKey> - <AcceptEula>true</AcceptEula> - <FullName>GPU-P</FullName> - <Organization> - </Organization> - </UserData> - </component> - </settings> - <settings pass="offlineServicing"> - <component name="Microsoft-Windows-LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <EnableLUA>true</EnableLUA> - </component> - </settings> - <settings pass="generalize"> - <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <SkipRearm>1</SkipRearm> - </component> - </settings> - <settings pass="specialize"> - <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <InputLocale>0409:00000409</InputLocale> - <SystemLocale>en-AU</SystemLocale> - <UILanguage>en-AU</UILanguage> - <UILanguageFallback>en-AU</UILanguageFallback> - <UserLocale>en-AU</UserLocale> - </component> - <component name="Microsoft-Windows-Security-SPP-UX" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <SkipAutoActivation>true</SkipAutoActivation> - </component> - <component name="Microsoft-Windows-SQMApi" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <CEIPEnabled>0</CEIPEnabled> - </component> - <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <ComputerName>GPUP122</ComputerName> - <ProductKey>W269N-WFGWX-YVC9B-4J6C9-T83GX</ProductKey> - </component> - </settings> - <settings pass="oobeSystem"> - <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <AutoLogon> - <Password> - <Value>CoolestPassword!</Value> - <PlainText>true</PlainText> - </Password> - <Enabled>true</Enabled> - <Username>GPUVM</Username> - </AutoLogon> - <OOBE> - <HideEULAPage>true</HideEULAPage> - <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen> - <HideOnlineAccountScreens>true</HideOnlineAccountScreens> - <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> - <NetworkLocation>Home</NetworkLocation> - <SkipUserOOBE>true</SkipUserOOBE> - <SkipMachineOOBE>true</SkipMachineOOBE> - <ProtectYourPC>1</ProtectYourPC> - </OOBE> - <Display> - <ColorDepth>32</ColorDepth> - <HorizontalResolution>1920</HorizontalResolution> - <RefreshRate>60</RefreshRate> - <VerticalResolution>1080</VerticalResolution> - </Display> - <UserAccounts> - <LocalAccounts> - <LocalAccount wcm:action="add"> - <Password> - <Value>CoolestPassword!</Value> - <PlainText>true</PlainText> - </Password> - <Description> - </Description> - <DisplayName>GPUVM</DisplayName> - <Group>Administrators</Group> - <Name>GPUVM</Name> - </LocalAccount> - </LocalAccounts> - </UserAccounts> - <RegisteredOrganization> - </RegisteredOrganization> - <RegisteredOwner>GPU-P</RegisteredOwner> - <DisableAutoDaylightTimeSet>false</DisableAutoDaylightTimeSet> - <FirstLogonCommands> - <SynchronousCommand wcm:action="add"> - <Description>Allow Scripts</Description> - <Order>1</Order> - <CommandLine>reg add HKLM\Software\Policies\Microsoft\Windows\Powershell</CommandLine> - <RequiresUserInput>false</RequiresUserInput> - </SynchronousCommand> - <SynchronousCommand wcm:action="add"> - <Description>Allow Scripts</Description> - <Order>2</Order> - <CommandLine>reg add HKLM\Software\Policies\Microsoft\Windows\Powershell /v ExecutionPolicy /t REG_SZ /d Unrestricted</CommandLine> - <RequiresUserInput>false</RequiresUserInput> - </SynchronousCommand> - <SynchronousCommand wcm:action="add"> - <Description>Allow Scripts</Description> - <Order>3</Order> - <CommandLine>reg add HKLM\Software\Policies\Microsoft\Windows\Powershell /v EnableScripts /t REG_DWORD /d 1</CommandLine> - <RequiresUserInput>false</RequiresUserInput> - </SynchronousCommand> - <SynchronousCommand wcm:action="add"> - <Order>4</Order> - <RequiresUserInput>false</RequiresUserInput> - <CommandLine>cmd /C wmic useraccount where name="GPU-P" set PasswordExpires=false</CommandLine> - <Description>Password Never Expires</Description> - </SynchronousCommand> - </FirstLogonCommands> - <TimeZone>GTB Standard Time</TimeZone> - </component> - </settings> -</unattend> \ No newline at end of file diff --git a/gpt.ini b/gpt.ini deleted file mode 100644 index 895c9bf..0000000 --- a/gpt.ini +++ /dev/null @@ -1,4 +0,0 @@ -[General] -gPCUserExtensionNames=[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B66650-4972-11D1-A7CA-0000F87571E3}] -Version=131074 -gPCMachineExtensionNames=[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}] \ No newline at end of file diff --git a/VMScripts/ParsecPublic.cer b/misc/ParsecPublic.cer similarity index 100% rename from VMScripts/ParsecPublic.cer rename to misc/ParsecPublic.cer