#Requires -Modules Hyper-V, Storage #Requires -RunAsAdministrator <# .SYNOPSIS A PowerShell script to create a Windows 10/11 FFU file. .DESCRIPTION This script creates a Windows 10/11 FFU and USB drive to help quickly get a Windows device reimaged. FFU can be customized with drivers, apps, and additional settings. .PARAMETER AllowExternalHardDiskMedia When set to $true, will allow the use of media identified as External Hard Disk media via WMI class Win32_DiskDrive. Default is not defined. .PARAMETER AllowVHDXCaching When set to $true, will cache the VHDX file to the $FFUDevelopmentPath\VHDXCache folder and create a config json file that will keep track of the Windows build information, the updates installed, and the logical sector byte size information. Default is $false. .PARAMETER AppsScriptVariables When passed a hashtable, the script will alter the $FFUDevelopmentPath\Apps\InstallAppsandSysprep.cmd file to set variables with the hashtable keys as variable names and the hashtable values their content. .PARAMETER BuildUSBDrive When set to $true, will partition and format a USB drive and copy the captured FFU to the drive. .PARAMETER CleanupAppsISO When set to $true, will remove the Apps ISO after the FFU has been captured. Default is $true. .PARAMETER CleanupCaptureISO When set to $true, will remove the WinPE capture ISO after the FFU has been captured. Default is $true. .PARAMETER CleanupDeployISO When set to $true, will remove the WinPE deployment ISO after the FFU has been captured. Default is $true. .PARAMETER CleanupDrivers When set to $true, will remove the drivers folder after the FFU has been captured. Default is $true. .PARAMETER CompactOS When set to $true, will compact the OS when building the FFU. Default is $true. .PARAMETER ConfigFile Path to a JSON file containing parameters to use for the script. Default is $null. .PARAMETER CopyAutopilot When set to $true, will copy the $FFUDevelopmentPath\Autopilot folder to the Deployment partition of the USB drive. Default is $false. .PARAMETER CopyDrivers When set to $true, will copy the drivers from the $FFUDevelopmentPath\Drivers folder to the Drivers folder on the deploy partition of the USB drive. Default is $false. .PARAMETER CopyPEDrivers When set to $true, will copy the drivers from the $FFUDevelopmentPath\PEDrivers folder to the WinPE deployment media. Default is $false. .PARAMETER CopyPPKG When set to $true, will copy the provisioning package from the $FFUDevelopmentPath\PPKG folder to the Deployment partition of the USB drive. Default is $false. .PARAMETER CopyUnattend When set to $true, will copy the $FFUDevelopmentPath\Unattend folder to the Deployment partition of the USB drive. Default is $false. .PARAMETER CreateCaptureMedia When set to $true, this will create WinPE capture media for use when $InstallApps is set to $true. This capture media will be automatically attached to the VM, and the boot order will be changed to automate the capture of the FFU. .PARAMETER CreateDeploymentMedia When set to $true, this will create WinPE deployment media for use when deploying to a physical device. .PARAMETER CustomFFUNameTemplate Sets a custom FFU output name with placeholders. Allowed placeholders are: {WindowsRelease}, {WindowsVersion}, {SKU}, {BuildDate}, {yyyy}, {MM}, {dd}, {H}, {hh}, {mm}, {tt}. .PARAMETER Disksize Size of the virtual hard disk for the virtual machine. Default is a 30GB dynamic disk. .PARAMETER DriversFolder Path to the drivers folder. Default is $FFUDevelopmentPath\Drivers. .PARAMETER ExportConfigFile Path to a JSON file to export the parameters used for the script. .PARAMETER FFUCaptureLocation Path to the folder where the captured FFU will be stored. Default is $FFUDevelopmentPath\FFU. .PARAMETER FFUDevelopmentPath Path to the FFU development folder. Default is C:\FFUDevelopment. .PARAMETER FFUPrefix Prefix for the generated FFU file. Default is _FFU. .PARAMETER Headers Headers to use when downloading files. Not recommended to modify. .PARAMETER InstallApps When set to $true, the script will create an Apps.iso file from the $FFUDevelopmentPath\Apps folder. It will also create a VM, mount the Apps.iso, install the apps, sysprep, and capture the VM. When set to $false, the FFU is created from a VHDX file, and no VM is created. .PARAMETER InstallDrivers Install device drivers from the specified $FFUDevelopmentPath\Drivers folder if set to $true. Download the drivers and put them in the Drivers folder. The script will recurse the drivers folder and add the drivers to the FFU. .PARAMETER InstallOffice Install Microsoft Office if set to $true. The script will download the latest ODT and Office files in the $FFUDevelopmentPath\Apps\Office folder and install Office in the FFU via VM. .PARAMETER ISOPath Path to the Windows 10/11 ISO file. .PARAMETER LogicalSectorSizeBytes Unit32 value of 512 or 4096. Useful for 4Kn drives or devices shipping with UFS drives. Default is 512. .PARAMETER Make Make of the device to download drivers. Accepted values are: 'Microsoft', 'Dell', 'HP', 'Lenovo'. .PARAMETER MediaType String value of either 'business' or 'consumer'. This is used to identify which media type to download. Default is 'consumer'. .PARAMETER Memory Amount of memory to allocate for the virtual machine. Recommended to use 8GB if possible, especially for Windows 11. Default is 4GB. .PARAMETER Model Model of the device to download drivers. This is required if Make is set. .PARAMETER Optimize When set to $true, will optimize the FFU file. Default is $true. .PARAMETER OptionalFeatures Provide a semicolon-separated list of Windows optional features you want to include in the FFU (e.g., netfx3;TFTP). .PARAMETER Processors Number of virtual processors for the virtual machine. Recommended to use at least 4. .PARAMETER ProductKey Product key for the Windows edition specified in WindowsSKU. This will overwrite whatever SKU is entered for WindowsSKU. Recommended to use if you want to use a MAK or KMS key to activate Enterprise or Education. If using VL media instead of consumer media, you'll want to enter a MAK or KMS key here. .PARAMETER PromptExternalHardDiskMedia When set to $true, will prompt the user to confirm the use of media identified as External Hard Disk media via WMI class Win32_DiskDrive. Default is $true. .PARAMETER RemoveFFU When set to $true, will remove the FFU file from the $FFUDevelopmentPath\FFU folder after it has been copied to the USB drive. Default is $false. .PARAMETER ShareName Name of the shared folder for FFU capture. The default is FFUCaptureShare. This share will be created with rights for the user account. When finished, the share will be removed. .PARAMETER UpdateEdge When set to $true, will download and install the latest Microsoft Edge for Windows 10/11. Default is $false. .PARAMETER UpdateLatestCU When set to $true, will download and install the latest cumulative update for Windows 10/11. Default is $false. .PARAMETER UpdatePreviewCU When set to $true, will download and install the latest Preview cumulative update for Windows 10/11. Default is $false. .PARAMETER UpdateLatestNet When set to $true, will download and install the latest .NET Framework for Windows 10/11. Default is $false. .PARAMETER UpdateLatestDefender When set to $true, will download and install the latest Windows Defender definitions and Defender platform update. Default is $false. .PARAMETER UpdateLatestMSRT When set to $true, will download and install the latest Windows Malicious Software Removal Tool. Default is $false. .PARAMETER UpdateLatestNet When set to $true, will download and install the latest .NET Framework for Windows 10/11. Default is $false. .PARAMETER UpdateOneDrive When set to $true, will download and install the latest OneDrive for Windows 10/11 and install it as a per-machine installation instead of per-user. Default is $false. .PARAMETER UpdatePreviewCU When set to $true, will download and install the latest Preview cumulative update for Windows 10/11. Default is $false. .PARAMETER UserAgent User agent string to use when downloading files. .PARAMETER Username Username for accessing the shared folder. The default is ffu_user. The script will auto-create the account and password. When finished, it will remove the account. .PARAMETER VMHostIPAddress IP address of the Hyper-V host for FFU capture. If $InstallApps is set to $true, this parameter must be configured. You must manually configure this. The script will not auto-detect your IP (depending on your network adapters, it may not find the correct IP). .PARAMETER VMLocation Default is $FFUDevelopmentPath\VM. This is the location of the VHDX that gets created where Windows will be installed to. .PARAMETER VMSwitchName Name of the Hyper-V virtual switch. If $InstallApps is set to $true, this must be set. This is required to capture the FFU from the VM. The default is '*external*', but you will likely need to change this. .PARAMETER WindowsArch String value of 'x86' or 'x64'. This is used to identify which architecture of Windows to download. Default is 'x64'. .PARAMETER WindowsLang String value in language-region format (e.g., 'en-us'). This is used to identify which language of media to download. Default is 'en-us'. .PARAMETER WindowsRelease Integer value of 10 or 11. This is used to identify which release of Windows to download. Default is 11. .PARAMETER WindowsSKU Edition of Windows 10/11 to be installed. Accepted values are: 'Home', 'Home N', 'Home Single Language', 'Education', 'Education N', 'Pro', 'Pro N', 'Pro Education', 'Pro Education N', 'Pro for Workstations', 'Pro N for Workstations', 'Enterprise', 'Enterprise N'. .PARAMETER WindowsVersion String value of the Windows version to download. This is used to identify which version of Windows to download. Default is '24h2'. .EXAMPLE Command line for most people who want to download the latest Windows 11 Pro x64 media in English (US) with the latest Windows Cumulative Update, .NET Framework, Defender platform and definition updates, Edge, OneDrive, and Office/M365 Apps. It will also copy drivers to the FFU. This can take about 40 minutes to create the FFU due to the time it takes to download and install the updates. .\BuildFFUVM.ps1 -WindowsSKU 'Pro' -Installapps $true -InstallOffice $true -InstallDrivers $true -VMSwitchName 'Name of your VM Switch in Hyper-V' -VMHostIPAddress 'Your IP Address' -CreateCaptureMedia $true -CreateDeploymentMedia $true -BuildUSBDrive $true -UpdateLatestCU $true -UpdateLatestNet $true -UpdateLatestDefender $true -UpdateEdge $true -UpdateOneDrive $true -verbose Command line for most people who want to create an FFU with Office and drivers and have downloaded their own ISO. This assumes you have copied this script and associated files to the C:\FFUDevelopment folder. If you need to use another drive or folder, change the -FFUDevelopment parameter (e.g. -FFUDevelopment 'D:\FFUDevelopment') .\BuildFFUVM.ps1 -ISOPath 'C:\path_to_iso\Windows.iso' -WindowsSKU 'Pro' -Installapps $true -InstallOffice $true -InstallDrivers $true -VMSwitchName 'Name of your VM Switch in Hyper-V' -VMHostIPAddress 'Your IP Address' -CreateCaptureMedia $true -CreateDeploymentMedia $true -BuildUSBDrive $true -verbose Command line for those who just want a FFU with no drivers, apps, or Office and have downloaded their own ISO. .\BuildFFUVM.ps1 -ISOPath 'C:\path_to_iso\Windows.iso' -WindowsSKU 'Pro' -Installapps $false -InstallOffice $false -InstallDrivers $false -CreateCaptureMedia $false -CreateDeploymentMedia $true -BuildUSBDrive $true -verbose Command line for those who just want a FFU with Apps and drivers, no Office and have downloaded their own ISO. .\BuildFFUVM.ps1 -ISOPath 'C:\path_to_iso\Windows.iso' -WindowsSKU 'Pro' -Installapps $true -InstallOffice $false -InstallDrivers $true -VMSwitchName 'Name of your VM Switch in Hyper-V' -VMHostIPAddress 'Your IP Address' -CreateCaptureMedia $true -CreateDeploymentMedia $true -BuildUSBDrive $true -verbose Command line for those who want to download the latest Windows 11 Pro x64 media in English (US) and install the latest version of Office and drivers. .\BuildFFUVM.ps1 -WindowsSKU 'Pro' -Installapps $true -InstallOffice $true -InstallDrivers $true -VMSwitchName 'Name of your VM Switch in Hyper-V' -VMHostIPAddress 'Your IP Address' -CreateCaptureMedia $true -CreateDeploymentMedia $true -BuildUSBDrive $true -verbose Command line for those who want to download the latest Windows 11 Pro x64 media in French (CA) and install the latest version of Office and drivers. .\BuildFFUVM.ps1 -WindowsSKU 'Pro' -Installapps $true -InstallOffice $true -InstallDrivers $true -VMSwitchName 'Name of your VM Switch in Hyper-V' -VMHostIPAddress 'Your IP Address' -CreateCaptureMedia $true -CreateDeploymentMedia $true -BuildUSBDrive $true -WindowsRelease 11 -WindowsArch 'x64' -WindowsLang 'fr-ca' -MediaType 'consumer' -verbose Command line for those who want to download the latest Windows 11 Pro x64 media in English (US) and install the latest version of Office and drivers. .\BuildFFUVM.ps1 -WindowsSKU 'Pro' -Installapps $true -InstallOffice $true -InstallDrivers $true -VMSwitchName 'Name of your VM Switch in Hyper-V' -VMHostIPAddress 'Your IP Address' -CreateCaptureMedia $true -CreateDeploymentMedia $true -BuildUSBDrive $true -verbose .NOTES Additional notes about your script. .LINK https://github.com/rbalsleyMSFT/FFU #> [CmdletBinding()] param( [Parameter(Mandatory = $false, Position = 0)] [ValidateScript({ Test-Path $_ })] [string]$ISOPath, [ValidateSet('Home', 'Home N', 'Home Single Language', 'Education', 'Education N', 'Pro', 'Pro N', 'Pro Education', 'Pro Education N', 'Pro for Workstations', 'Pro N for Workstations', 'Enterprise', 'Enterprise N', 'Standard', 'Standard (Desktop Experience)', 'Datacenter', 'Datacenter (Desktop Experience)')] [string]$WindowsSKU = 'Pro', [ValidateScript({ Test-Path $_ })] [string]$FFUDevelopmentPath = $PSScriptRoot, [bool]$InstallApps, [hashtable]$AppsScriptVariables, [bool]$InstallOffice, [ValidateSet('Microsoft', 'Dell', 'HP', 'Lenovo')] [string]$Make, [string]$Model, [bool]$InstallDrivers, [uint64]$Memory = 4GB, [uint64]$Disksize = 30GB, [int]$Processors = 4, [string]$VMSwitchName, [string]$VMLocation, [string]$FFUPrefix = '_FFU', [string]$FFUCaptureLocation, [string]$ShareName = "FFUCaptureShare", [string]$Username = "ffu_user", [string]$CustomFFUNameTemplate, [Parameter(Mandatory = $false)] [string]$VMHostIPAddress, [bool]$CreateCaptureMedia = $true, [bool]$CreateDeploymentMedia, [ValidateScript({ $allowedFeatures = @("Windows-Defender-Default-Definitions", "Printing-PrintToPDFServices-Features", "Printing-XPSServices-Features", "TelnetClient", "TFTP", "TIFFIFilter", "LegacyComponents", "DirectPlay", "MSRDC-Infrastructure", "Windows-Identity-Foundation", "MicrosoftWindowsPowerShellV2Root", "MicrosoftWindowsPowerShellV2", "SimpleTCP", "NetFx4-AdvSrvs", "NetFx4Extended-ASPNET45", "WCF-Services45", "WCF-HTTP-Activation45", "WCF-TCP-Activation45", "WCF-Pipe-Activation45", "WCF-MSMQ-Activation45", "WCF-TCP-PortSharing45", "IIS-WebServerRole", "IIS-WebServer", "IIS-CommonHttpFeatures", "IIS-HttpErrors", "IIS-HttpRedirect", "IIS-ApplicationDevelopment", "IIS-Security", "IIS-RequestFiltering", "IIS-NetFxExtensibility", "IIS-NetFxExtensibility45", "IIS-HealthAndDiagnostics", "IIS-HttpLogging", "IIS-LoggingLibraries", "IIS-RequestMonitor", "IIS-HttpTracing", "IIS-URLAuthorization", "IIS-IPSecurity", "IIS-Performance", "IIS-HttpCompressionDynamic", "IIS-WebServerManagementTools", "IIS-ManagementScriptingTools", "IIS-IIS6ManagementCompatibility", "IIS-Metabase", "WAS-WindowsActivationService", "WAS-ProcessModel", "WAS-NetFxEnvironment", "WAS-ConfigurationAPI", "IIS-HostableWebCore", "WCF-HTTP-Activation", "WCF-NonHTTP-Activation", "IIS-StaticContent", "IIS-DefaultDocument", "IIS-DirectoryBrowsing", "IIS-WebDAV", "IIS-WebSockets", "IIS-ApplicationInit", "IIS-ISAPIFilter", "IIS-ISAPIExtensions", "IIS-ASPNET", "IIS-ASPNET45", "IIS-ASP", "IIS-CGI", "IIS-ServerSideIncludes", "IIS-CustomLogging", "IIS-BasicAuthentication", "IIS-HttpCompressionStatic", "IIS-ManagementConsole", "IIS-ManagementService", "IIS-WMICompatibility", "IIS-LegacyScripts", "IIS-LegacySnapIn", "IIS-FTPServer", "IIS-FTPSvc", "IIS-FTPExtensibility", "MSMQ-Container", "MSMQ-DCOMProxy", "MSMQ-Server", "MSMQ-ADIntegration", "MSMQ-HTTP", "MSMQ-Multicast", "MSMQ-Triggers", "IIS-CertProvider", "IIS-WindowsAuthentication", "IIS-DigestAuthentication", "IIS-ClientCertificateMappingAuthentication", "IIS-IISCertificateMappingAuthentication", "IIS-ODBCLogging", "NetFx3", "SMB1Protocol-Deprecation", "MediaPlayback", "WindowsMediaPlayer", "Client-DeviceLockdown", "Client-EmbeddedShellLauncher", "Client-EmbeddedBootExp", "Client-EmbeddedLogon", "Client-KeyboardFilter", "Client-UnifiedWriteFilter", "HostGuardian", "MultiPoint-Connector", "MultiPoint-Connector-Services", "MultiPoint-Tools" , "AppServerClient", "SearchEngine-Client-Package", "WorkFolders-Client", "Printing-Foundation-Features", "Printing-Foundation-InternetPrinting-Client", "Printing-Foundation-LPDPrintService", "Printing-Foundation-LPRPortMonitor", "HypervisorPlatform", "VirtualMachinePlatform", "Microsoft-Windows-Subsystem-Linux", "Client-ProjFS", "Containers-DisposableClientVM", 'Containers-DisposableClientVM', 'Microsoft-Hyper-V-All', 'Microsoft-Hyper-V', 'Microsoft-Hyper-V-Tools-All', 'Microsoft-Hyper-V-Management-PowerShell', 'Microsoft-Hyper-V-Hypervisor', 'Microsoft-Hyper-V-Services', 'Microsoft-Hyper-V-Management-Clients', 'DataCenterBridging', 'DirectoryServices-ADAM-Client', 'Windows-Defender-ApplicationGuard', 'ServicesForNFS-ClientOnly', 'ClientForNFS-Infrastructure', 'NFS-Administration', 'Containers', 'Containers-HNS', 'Containers-SDN', 'SMB1Protocol', 'SMB1Protocol-Client', 'SMB1Protocol-Server', 'SmbDirect') $inputFeatures = $_ -split ';' foreach ($feature in $inputFeatures) { if (-not ($allowedFeatures -contains $feature)) { throw "Invalid optional feature '$feature'. Allowed values: $($allowedFeatures -join ', ')" } } return $true })] [string]$OptionalFeatures, [string]$ProductKey, [bool]$BuildUSBDrive, [Parameter(Mandatory = $false)] [ValidateSet(10, 11, 2016, 2019, 2022, 2025)] [int]$WindowsRelease = 11, [Parameter(Mandatory = $false)] [string]$WindowsVersion = '24h2', [Parameter(Mandatory = $false)] [ValidateSet('x86', 'x64', 'arm64')] [string]$WindowsArch = 'x64', [ValidateScript({ $allowedLang = @('ar-sa', 'bg-bg', 'cs-cz', 'da-dk', 'de-de', 'el-gr', 'en-gb', 'en-us', 'es-es', 'es-mx', 'et-ee', 'fi-fi', 'fr-ca', 'fr-fr', 'he-il', 'hr-hr', 'hu-hu', 'it-it', 'ja-jp', 'ko-kr', 'lt-lt', 'lv-lv', 'nb-no', 'nl-nl', 'pl-pl', 'pt-br', 'pt-pt', 'ro-ro', 'ru-ru', 'sk-sk', 'sl-si', 'sr-latn-rs', 'sv-se', 'th-th', 'tr-tr', 'uk-ua', 'zh-cn', 'zh-tw') if ($allowedLang -contains $_) { $true } else { throw "Invalid WindowsLang value. Allowed values: $($allowedLang -join ', ')" } return $true })] [Parameter(Mandatory = $false)] [string]$WindowsLang = 'en-us', [Parameter(Mandatory = $false)] [ValidateSet('consumer', 'business')] [string]$MediaType = 'consumer', [ValidateSet(512, 4096)] [uint32]$LogicalSectorSizeBytes = 512, [bool]$Optimize = $true, [Parameter(Mandatory = $false)] [ValidateScript({ if ($Make) { return $true } if ($_ -and (!(Test-Path -Path '.\Drivers') -or ((Get-ChildItem -Path '.\Drivers' -Recurse | Measure-Object -Property Length -Sum).Sum -lt 1MB))) { throw 'CopyDrivers is set to $true, but either the Drivers folder is missing or empty' } return $true })] [bool]$CopyDrivers, [bool]$CopyPEDrivers, [bool]$RemoveFFU, [bool]$UpdateLatestCU, [bool]$UpdatePreviewCU, [bool]$UpdateLatestNet, [bool]$UpdateLatestDefender, [bool]$UpdateLatestMSRT, [bool]$UpdateEdge, [bool]$UpdateOneDrive, [bool]$AllowVHDXCaching, [bool]$CopyPPKG, [bool]$CopyUnattend, [bool]$CopyAutopilot, [bool]$CompactOS = $true, [bool]$CleanupCaptureISO = $true, [bool]$CleanupDeployISO = $true, [bool]$CleanupAppsISO = $true, [string]$DriversFolder, [string]$PEDriversFolder, [bool]$CleanupDrivers = $true, [string]$UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0', #Microsoft sites will intermittently fail on downloads. These headers are to help with that. $Headers = @{ "Accept" = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7" "Accept-Encoding" = "gzip, deflate, br, zstd" "Accept-Language" = "en-US,en;q=0.9" "Priority" = "u=0, i" "Sec-Ch-Ua" = "`"Microsoft Edge`";v=`"125`", `"Chromium`";v=`"125`", `"Not.A/Brand`";v=`"24`"" "Sec-Ch-Ua-Mobile" = "?0" "Sec-Ch-Ua-Platform" = "`"Windows`"" "Sec-Fetch-Dest" = "document" "Sec-Fetch-Mode" = "navigate" "Sec-Fetch-Site" = "none" "Sec-Fetch-User" = "?1" "Upgrade-Insecure-Requests" = "1" }, [bool]$AllowExternalHardDiskMedia, [bool]$PromptExternalHardDiskMedia = $true, [Parameter(Mandatory = $false)] [ValidateScript({ $_ -eq $null -or (Test-Path $_) })] [string]$ConfigFile, [Parameter(Mandatory = $false)] [string]$ExportConfigFile ) $version = '2412.3' # If a config file is specified and it exists, load it if ($ConfigFile -and (Test-Path -Path $ConfigFile)) { $configData = Get-Content $ConfigFile -Raw | ConvertFrom-Json $keys = $configData.psobject.Properties.Name # Iterate through the keys in the config data foreach ($key in $keys) { $value = $configdata.$key # If $value is empty, skip if ($null -eq $value -or ([string]::IsNullOrEmpty([string]$value)) -or ($value -is [System.Collections.Hashtable] -and $value.Count -eq 0) -or ($value -is [System.UInt32] -and $value -eq 0) -or ($value -is [System.UInt64] -and $value -eq 0) -or ($value -is [System.Int32] -and $value -eq 0)) { continue } # If this is the Headers parameter, convert PSCustomObject to hashtable if ($key -eq 'Headers' -and $value -is [System.Management.Automation.PSCustomObject]) { $headers = [hashtable]::new() foreach ($prop in $value.psobject.Properties) { $headers[$prop.Name] = $prop.Value } $value = $headers } # Check if this key matches a parameter in the script # and if the user did NOT explicitly supply it on the command line if ($MyInvocation.MyCommand.Parameters.ContainsKey($key) -and -not $PSBoundParameters.ContainsKey($key)) { # Set the parameter's value to what's in the config file Set-Variable -Name $key -Value $value -Scope 0 } } } #Class definition for vhdx cache class VhdxCacheUpdateItem { [string]$Name VhdxCacheUpdateItem([string]$Name) { $this.Name = $Name } } class VhdxCacheItem { [string]$VhdxFileName = "" [uint32]$LogicalSectorSizeBytes = "" [string]$WindowsSKU = "" [string]$WindowsRelease = "" [string]$WindowsVersion = "" [string]$OptionalFeatures = "" [VhdxCacheUpdateItem[]]$IncludedUpdates = @() } #Check if Hyper-V feature is installed (requires only checks the module) $osInfo = Get-WmiObject -Class Win32_OperatingSystem $isServer = $osInfo.Caption -match 'server' if ($isServer) { $hyperVFeature = Get-WindowsFeature -Name Hyper-V if ($hyperVFeature.InstallState -ne "Installed") { Write-Host "Hyper-V feature is not installed. Please install it before running this script." exit } } else { $hyperVFeature = Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All if ($hyperVFeature.State -ne "Enabled") { Write-Host "Hyper-V feature is not enabled. Please enable it before running this script." exit } } # Set default values for variables that depend on other parameters if (-not $AppsISO) { $AppsISO = "$FFUDevelopmentPath\Apps.iso" } if (-not $AppsPath) { $AppsPath = "$FFUDevelopmentPath\Apps" } if (-not $DeployISO) { $DeployISO = "$FFUDevelopmentPath\WinPE_FFU_Deploy_$WindowsArch.iso" } if (-not $CaptureISO) { $CaptureISO = "$FFUDevelopmentPath\WinPE_FFU_Capture_$WindowsArch.iso" } if (-not $OfficePath) { $OfficePath = "$AppsPath\Office" } if (-not $rand) { $rand = Get-Random } if (-not $VMLocation) { $VMLocation = "$FFUDevelopmentPath\VM" } if (-not $VMName) { $VMName = "$FFUPrefix-$rand" } if (-not $VMPath) { $VMPath = "$VMLocation\$VMName" } if (-not $VHDXPath) { $VHDXPath = "$VMPath\$VMName.vhdx" } if (-not $FFUCaptureLocation) { $FFUCaptureLocation = "$FFUDevelopmentPath\FFU" } if (-not $LogFile) { $LogFile = "$FFUDevelopmentPath\FFUDevelopment.log" } if (-not $KBPath) { $KBPath = "$FFUDevelopmentPath\KB" } if (-not $DefenderPath) { $DefenderPath = "$AppsPath\Defender" } if (-not $MSRTPath) { $MSRTPath = "$AppsPath\MSRT" } if (-not $OneDrivePath) { $OneDrivePath = "$AppsPath\OneDrive" } if (-not $EdgePath) { $EdgePath = "$AppsPath\Edge" } if (-not $DriversFolder) { $DriversFolder = "$FFUDevelopmentPath\Drivers" } if (-not $PPKGFolder) { $PPKGFolder = "$FFUDevelopmentPath\PPKG" } if (-not $UnattendFolder) { $UnattendFolder = "$FFUDevelopmentPath\Unattend" } if (-not $AutopilotFolder) { $AutopilotFolder = "$FFUDevelopmentPath\Autopilot" } if (-not $PEDriversFolder) { $PEDriversFolder = "$FFUDevelopmentPath\PEDrivers" } if (-not $VHDXCacheFolder) { $VHDXCacheFolder = "$FFUDevelopmentPath\VHDXCache" } if (-not $installationType) { $installationType = if ($WindowsRelease.ToString().Length -eq 2) { 'Client' } else { 'Server' } } if ($installationType -eq 'Server'){ #Map $WindowsRelease to $WindowsVersion for Windows Server switch ($WindowsRelease) { 2016 { $WindowsVersion = '1607' } 2019 { $WindowsVersion = '1809' } 2022 { $WindowsVersion = '21H2' } 2025 { $WindowsVersion = '24H2' } } } #FUNCTIONS function WriteLog($LogText) { Add-Content -path $LogFile -value "$((Get-Date).ToString()) $LogText" -Force -ErrorAction SilentlyContinue Write-Verbose $LogText } function Get-Parameters{ [CmdletBinding()] param ( [Parameter()] $ParamNames ) # Define unwanted parameters $excludedParams = 'Debug','ErrorAction','ErrorVariable','InformationAction','InformationVariable','OutBuffer','OutVariable','PipelineVariable','Verbose','WarningAction','WarningVariable' # Filter out the unwanted parameters $filteredParamNames = $paramNames | Where-Object { $excludedParams -notcontains $_ } return $filteredParamNames } function LogVariableValues { $excludedVariables = @( 'PSBoundParameters', 'PSScriptRoot', 'PSCommandPath', 'MyInvocation', '?', 'ConsoleFileName', 'ExecutionContext', 'false', 'HOME', 'Host', 'hyperVFeature', 'input', 'MaximumAliasCount', 'MaximumDriveCount', 'MaximumErrorCount', 'MaximumFunctionCount', 'MaximumVariableCount', 'null', 'PID', 'PSCmdlet', 'PSCulture', 'PSUICulture', 'PSVersionTable', 'ShellId', 'true' ) $allVariables = Get-Variable -Scope Script | Where-Object { $_.Name -notin $excludedVariables } Writelog "Script version: $version" WriteLog 'Logging variables' foreach ($variable in $allVariables) { $variableName = $variable.Name $variableValue = $variable.Value if ($null -ne $variableValue) { WriteLog "[VAR]$variableName`: $variableValue" } else { WriteLog "[VAR]Variable $variableName not found or not set" } } WriteLog 'End logging variables' } function Get-ChildProcesses($parentId) { $result = @() $children = Get-CimInstance Win32_Process -Filter "ParentProcessId = $parentId" foreach ($child in $children) { $result += $child $result += Get-ChildProcesses $child.ProcessId } return $result } function Invoke-Process { [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$FilePath, [Parameter()] [ValidateNotNullOrEmpty()] [string[]]$ArgumentList, [Parameter()] [ValidateNotNullOrEmpty()] [bool]$Wait = $true ) $ErrorActionPreference = 'Stop' try { $stdOutTempFile = "$env:TEMP\$((New-Guid).Guid)" $stdErrTempFile = "$env:TEMP\$((New-Guid).Guid)" $startProcessParams = @{ FilePath = $FilePath ArgumentList = $ArgumentList RedirectStandardError = $stdErrTempFile RedirectStandardOutput = $stdOutTempFile Wait = $($Wait); PassThru = $true; NoNewWindow = $true; } if ($PSCmdlet.ShouldProcess("Process [$($FilePath)]", "Run with args: [$($ArgumentList)]")) { $cmd = Start-Process @startProcessParams $cmdOutput = Get-Content -Path $stdOutTempFile -Raw $cmdError = Get-Content -Path $stdErrTempFile -Raw if ($cmd.ExitCode -ne 0 -and $wait -eq $true) { if ($cmdError) { throw $cmdError.Trim() } if ($cmdOutput) { throw $cmdOutput.Trim() } } else { if ([string]::IsNullOrEmpty($cmdOutput) -eq $false) { WriteLog $cmdOutput } } } } catch { #$PSCmdlet.ThrowTerminatingError($_) WriteLog $_ # Write-Host "Script failed - $Logfile for more info" throw $_ } finally { Remove-Item -Path $stdOutTempFile, $stdErrTempFile -Force -ErrorAction Ignore } return $cmd } function Test-Url { param ( [Parameter(Mandatory = $true)] [string]$Url ) try { # Create a web request and check the response $request = [System.Net.WebRequest]::Create($Url) $request.Method = 'HEAD' $response = $request.GetResponse() return $true } catch { return $false } } # Function to download a file using BITS with retry and error handling function Start-BitsTransferWithRetry { param ( [Parameter(Mandatory = $true)] [string]$Source, [Parameter(Mandatory = $true)] [string]$Destination, [int]$Retries = 3 ) $attempt = 0 while ($attempt -lt $Retries) { try { $OriginalVerbosePreference = $VerbosePreference $VerbosePreference = 'SilentlyContinue' $ProgressPreference = 'SilentlyContinue' Start-BitsTransfer -Source $Source -Destination $Destination -ErrorAction Stop $ProgressPreference = 'Continue' $VerbosePreference = $OriginalVerbosePreference return } catch { $attempt++ WriteLog "Attempt $attempt of $Retries failed to download $Source. Retrying..." Start-Sleep -Seconds 5 } } WriteLog "Failed to download $Source after $Retries attempts." return $false } function Get-MicrosoftDrivers { param ( [string]$Make, [string]$Model, [int]$WindowsRelease ) $url = "https://support.microsoft.com/en-us/surface/download-drivers-and-firmware-for-surface-09bb2e09-2a4b-cb69-0951-078a7739e120" # Download the webpage content WriteLog "Getting Surface driver information from $url" $OriginalVerbosePreference = $VerbosePreference $VerbosePreference = 'SilentlyContinue' $webContent = Invoke-WebRequest -Uri $url -UseBasicParsing -Headers $Headers -UserAgent $UserAgent $VerbosePreference = $OriginalVerbosePreference WriteLog "Complete" # Parse the HTML content using Regex instead of the HTMLFILE COM object WriteLog "Parsing web content for models and download links" $html = $webContent.Content # Regex to match divs with selectable-content-options__option-content classes $divPattern = ']*class="selectable-content-options__option-content(?: ocHidden)?"[^>]*>(.*?)' $divMatches = [regex]::Matches($html, $divPattern, [System.Text.RegularExpressions.RegexOptions]::Singleline) $models = @() foreach ($divMatch in $divMatches) { $divContent = $divMatch.Groups[1].Value # Find all tables within the div $tablePattern = ']*>(.*?)' $tableMatches = [regex]::Matches($divContent, $tablePattern, [System.Text.RegularExpressions.RegexOptions]::Singleline) foreach ($tableMatch in $tableMatches) { $tableContent = $tableMatch.Groups[1].Value # Find all rows in the table $rowPattern = ']*>(.*?)' $rowMatches = [regex]::Matches($tableContent, $rowPattern, [System.Text.RegularExpressions.RegexOptions]::Singleline) foreach ($rowMatch in $rowMatches) { $rowContent = $rowMatch.Groups[1].Value # Extract cells from the row $cellPattern = ']*>\s*(?:]*>)?(.*?)(?:

)?\s*' $cellMatches = [regex]::Matches($rowContent, $cellPattern, [System.Text.RegularExpressions.RegexOptions]::Singleline) if ($cellMatches.Count -ge 2) { # Model name in the first TD $modelName = ($cellMatches[0].Groups[1].Value).Trim() # # Remove

and

tags if present # $modelName = $modelName -replace ']*>', '' -replace '

', '' # $modelName = $modelName.Trim() # The second TD might contain a link or just text $secondTdContent = $cellMatches[1].Groups[1].Value.Trim() # Look for a link in the second TD $linkPattern = ']+href="([^"]+)"[^>]*>' $linkMatch = [regex]::Match($secondTdContent, $linkPattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) if ($linkMatch.Success) { $modelLink = $linkMatch.Groups[1].Value } else { # No link, just text instructions $modelLink = $secondTdContent } $models += [PSCustomObject]@{ Model = $modelName; Link = $modelLink } } } } } WriteLog "Parsing complete" # Validate the model $selectedModel = $models | Where-Object { $_.Model -eq $Model } if ($null -eq $selectedModel) { if ($VerbosePreference -ne 'Continue') { Write-Host "The model '$Model' was not found in the list of available models." Write-Host "Please run the script with the -Verbose switch to see the list of available models." } WriteLog "The model '$Model' was not found in the list of available models." WriteLog "Please select a model from the list below by number:" for ($i = 0; $i -lt $models.Count; $i++) { if ($VerbosePreference -ne 'Continue') { Write-Host "$($i + 1). $($models[$i].Model)" } WriteLog "$($i + 1). $($models[$i].Model)" } do { $selection = Read-Host "Enter the number of the model you want to select" WriteLog "User selected model number: $selection" if ($selection -match '^\d+$' -and [int]$selection -ge 1 -and [int]$selection -le $models.Count) { $selectedModel = $models[$selection - 1] } else { if ($VerbosePreference -ne 'Continue') { Write-Host "Invalid selection. Please try again." } WriteLog "Invalid selection. Please try again." } } while ($null -eq $selectedModel) } $Model = $selectedModel.Model WriteLog "Model: $Model" WriteLog "Download Page: $($selectedModel.Link)" # Follow the link to the download page and parse the script tag WriteLog "Getting download page content" $OriginalVerbosePreference = $VerbosePreference $VerbosePreference = 'SilentlyContinue' $downloadPageContent = Invoke-WebRequest -Uri $selectedModel.Link -UseBasicParsing -Headers $Headers -UserAgent $UserAgent $VerbosePreference = $OriginalVerbosePreference WriteLog "Complete" WriteLog "Parsing download page for file" $scriptPattern = '