| 1 | param([switch]$Prepare) |
| 2 | $ErrorActionPreference = 'Stop' |
| 3 | $ProgressPreference = 'SilentlyContinue' |
| 4 | $root = 'C:\Snowglobe' |
| 5 | $status = Join-Path $root 'setup' |
| 6 | $winlogon = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' |
| 7 | $scheduler = New-Object -ComObject Schedule.Service |
| 8 | $scheduler.Connect() |
| 9 | $folder = $scheduler.GetFolder('\') |
| 10 | |
| 11 | function Set-GuestPassword([string]$name, [string]$password) { |
| 12 | $account = [ADSI]("WinNT://" + $env:COMPUTERNAME + "/" + $name + ",user") |
| 13 | $account.SetPassword($password) |
| 14 | $account.UserFlags = ([int]$account.UserFlags.Value -bor 0x10000) -band (-bnot 2) |
| 15 | $account.PasswordExpired = 0 |
| 16 | $account.SetInfo() |
| 17 | } |
| 18 | |
| 19 | function Set-SetupStatus([string]$stage) { |
| 20 | $path = Join-Path $status $stage |
| 21 | if (!(Test-Path $path)) { |
| 22 | [IO.File]::Open($path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite).Dispose() |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | try { |
| 27 | if ($Prepare) { |
| 28 | Remove-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run' -Name SnowglobeBootstrap -ErrorAction SilentlyContinue |
| 29 | foreach ($task in $folder.GetTasks(1)) { |
| 30 | if ($task.Name -eq 'SnowglobeFinalize' -or $task.Name -eq 'SnowglobeBootstrap') { $task.Stop(0); $folder.DeleteTask($task.Name, 0) } |
| 31 | } |
| 32 | & "$root\install-guest.ps1" -Binary "$root\snowglobe-guest.exe" -User sandbox |
| 33 | $user = Get-WmiObject Win32_UserAccount -Filter "LocalAccount=True AND Name='sandbox'" |
| 34 | if (!$user) { throw 'The template account is missing.' } |
| 35 | $user.SID | Set-Content "$root\template.sid" -Encoding ASCII |
| 36 | foreach ($task in $folder.GetTasks(1)) { |
| 37 | if ($task.Name -like 'SnowglobeGuest-*') { $task.Enabled = $false } |
| 38 | } |
| 39 | Get-Process snowglobe-guest -ErrorAction SilentlyContinue | Stop-Process -Force |
| 40 | $task = $scheduler.NewTask(0) |
| 41 | $task.Principal.UserId = 'SYSTEM' |
| 42 | $task.Principal.LogonType = 5 |
| 43 | $task.Principal.RunLevel = 1 |
| 44 | $task.Settings.StartWhenAvailable = $true |
| 45 | $task.Settings.ExecutionTimeLimit = 'PT15M' |
| 46 | $task.Settings.Priority = 4 |
| 47 | $task.Triggers.Create(8) | Out-Null |
| 48 | $action = $task.Actions.Create(0) |
| 49 | $action.Path = "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" |
| 50 | $action.Arguments = '-NoProfile -ExecutionPolicy Bypass -File C:\Snowglobe\windows-provision.ps1' |
| 51 | $folder.RegisterTaskDefinition('SnowglobeProvision', $task, 6, 'SYSTEM', $null, 5, $null) | Out-Null |
| 52 | $password = [Guid]::NewGuid().ToString('N') + [Guid]::NewGuid().ToString('N') |
| 53 | Set-GuestPassword sandbox $password |
| 54 | Set-ItemProperty $winlogon AutoAdminLogon '1' |
| 55 | Set-ItemProperty $winlogon DefaultUserName 'sandbox' |
| 56 | Set-ItemProperty $winlogon DefaultDomainName $env:COMPUTERNAME |
| 57 | Set-ItemProperty $winlogon DefaultPassword $password |
| 58 | Remove-ItemProperty $winlogon AutoLogonCount -ErrorAction SilentlyContinue |
| 59 | powercfg.exe /hibernate off |
| 60 | Remove-Item "$root\identity.ini", "$root\provisioned" -Force -ErrorAction SilentlyContinue |
| 61 | if (Test-Path $status) { Remove-Item $status -Recurse -Force } |
| 62 | return |
| 63 | } |
| 64 | |
| 65 | New-Item $status -ItemType Directory -Force | Out-Null |
| 66 | if (Test-Path "$status\ready") { return } |
| 67 | if (Test-Path "$status\failed") { Remove-Item "$status\failed" -Force } |
| 68 | Set-SetupStatus personalizing |
| 69 | $seed = $null |
| 70 | $deadline = (Get-Date).AddMinutes(1) |
| 71 | while (!$seed) { |
| 72 | $seed = 68..90 | ForEach-Object { '{0}:\SNOWGLOB.INI' -f [char]$_ } | Where-Object { Test-Path $_ } | Select-Object -First 1 |
| 73 | if ($seed) { break } |
| 74 | if ((Get-Date) -gt $deadline) { throw 'The VM login was not attached.' } |
| 75 | Start-Sleep -Milliseconds 250 |
| 76 | } |
| 77 | $values = @{} |
| 78 | foreach ($line in Get-Content $seed) { |
| 79 | $pair = $line.Split('=', 2) |
| 80 | if ($pair.Count -eq 2) { $values[$pair[0]] = $pair[1] } |
| 81 | } |
| 82 | $username = $values['USERNAME'] |
| 83 | $password = $values['PASSWORD'] |
| 84 | if ($username -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,19}$') { throw 'The VM account name is unsupported.' } |
| 85 | if ($password.Length -lt 12 -or $password.Length -gt 128 -or $password -match '[\r\n]') { throw 'The VM password is malformed.' } |
| 86 | $sid = Get-Content "$root\template.sid" |
| 87 | $user = Get-WmiObject Win32_UserAccount -Filter "LocalAccount=True AND SID='$sid'" |
| 88 | if (!$user) { throw 'The template account is missing.' } |
| 89 | if (Get-WmiObject Win32_UserAccount -Filter "LocalAccount=True AND Name='$username'" | Where-Object { $_.SID -ne $sid }) { throw 'The VM account name is already in use.' } |
| 90 | $deadline = (Get-Date).AddMinutes(10) |
| 91 | function Find-Desktop { |
| 92 | Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" | Where-Object { |
| 93 | $_.SessionId -gt 0 -and $_.GetOwnerSid().Sid -eq $sid |
| 94 | } | Select-Object -First 1 |
| 95 | } |
| 96 | $desktop = Find-Desktop |
| 97 | while (!$desktop) { |
| 98 | if ((Get-Date) -gt $deadline) { throw 'The template desktop did not start.' } |
| 99 | Start-Sleep -Milliseconds 250 |
| 100 | $desktop = Find-Desktop |
| 101 | } |
| 102 | # Windows 7 cannot resolve the old task principal after the account is renamed. |
| 103 | $definition = $folder.GetTask("SnowglobeGuest-$sid").Definition |
| 104 | Set-GuestPassword $user.Name $password |
| 105 | if ($user.Name -ine $username -and $user.Rename($username).ReturnValue -ne 0) { throw 'The template account could not be renamed.' } |
| 106 | Set-ItemProperty $winlogon AutoAdminLogon '1' |
| 107 | Set-ItemProperty $winlogon DefaultUserName $username |
| 108 | Set-ItemProperty $winlogon DefaultDomainName $env:COMPUTERNAME |
| 109 | Set-ItemProperty $winlogon DefaultPassword $password |
| 110 | Remove-ItemProperty $winlogon AutoLogonCount -ErrorAction SilentlyContinue |
| 111 | $definition.Principal.UserId = $sid |
| 112 | $definition.Triggers.Item(1).UserId = $sid |
| 113 | $definition.Settings.Enabled = $true |
| 114 | $task = $folder.RegisterTaskDefinition("SnowglobeGuest-$sid", $definition, 6, $sid, $null, 3, $null) |
| 115 | Set-ItemProperty $winlogon ForceAutoLogon '1' |
| 116 | Set-SetupStatus signingIn |
| 117 | & "$env:WINDIR\System32\logoff.exe" $desktop.SessionId |
| 118 | if ($LASTEXITCODE -ne 0) { throw 'The template session could not sign out.' } |
| 119 | do { |
| 120 | if ((Get-Date) -gt $deadline) { throw 'The personalized desktop did not start.' } |
| 121 | Start-Sleep -Milliseconds 250 |
| 122 | $fresh = Find-Desktop |
| 123 | } while (!$fresh -or ($fresh.ProcessId -eq $desktop.ProcessId -and $fresh.CreationDate -eq $desktop.CreationDate)) |
| 124 | $task.Run($null) | Out-Null |
| 125 | do { |
| 126 | if ((Get-Date) -gt $deadline) { throw 'Desktop capture did not start.' } |
| 127 | Start-Sleep -Milliseconds 250 |
| 128 | $capture = Get-WmiObject Win32_Process -Filter "Name='snowglobe-guest.exe'" | Where-Object { |
| 129 | $_.SessionId -eq $fresh.SessionId -and $_.GetOwnerSid().Sid -eq $sid |
| 130 | } |
| 131 | } while (!$capture) |
| 132 | Set-SetupStatus ready |
| 133 | } catch { |
| 134 | if ($Prepare) { throw } |
| 135 | Set-SetupStatus failed |
| 136 | Add-Content "$root\setup.log" $_.Exception.Message |
| 137 | exit 1 |
| 138 | } |
| 139 | finally { |
| 140 | Remove-ItemProperty $winlogon ForceAutoLogon -ErrorAction SilentlyContinue |
| 141 | } |