
param(
    [Parameter(Mandatory = $true)]
    [string]$ProductKey,
    [Parameter(Mandatory = $true)]
    [string]$AdministratorPassword,
    [Parameter(Mandatory = $true)]
    [string]$autounattendXmlFile,
    [Parameter(Mandatory = $true)]
    [string]$isoOutputDir,
    [Parameter(Mandatory = $true)]
    [string]$isoOutputPath    
)

# cleanup
Get-ChildItem -Path $isoOutputDir | Remove-Item -Force

# Create a directory to hold the autounattend.xml file
New-Item -ItemType Directory -Path $isoOutputDir -Force | Out-Null

# Copy the autounattend.xml file to this directory
Copy-Item -Path $autounattendXmlFile -Destination $isoOutputDir

$autounattendXmlFile = "$isoOutputDir\autounattend.xml"

# Load the XML template
[xml]$xmlContent = Get-Content -Path $autounattendXmlFile

# Replace the ProductKey element value
$xmlContent.unattend.settings.component.UserData.ProductKey.Key = $productKey
$xmlContent.unattend.settings.component.UserAccounts.AdministratorPassword.Value = $AdministratorPassword
$xmlContent.unattend.settings.component.AutoLogon.Password.Value = $AdministratorPassword
# Save the modified XML to the destination path
$xmlContent.Save($autounattendXmlFile)

# Create an ISO from the directory
$process = Start-Process -FilePath "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\x86\Oscdimg\oscdimg.exe" -ArgumentList "-m", "-o", "-u2", $isoOutputDir, $isoOutputPath -Wait -PassThru
if($process.ExitCode -ne 0)
{
    $processError = $process.StandardError.ReadToEnd()
    throw "CreateAutounattendISO failed: $processError"
}