-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathAtlasImage.ps1
229 lines (193 loc) · 9.28 KB
/
AtlasImage.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
Param (
[string]$emailTo,
[string]$smtpServer,
[string]$emailFrom,
[string]$sysprep,
[string]$stripDISM
)
$scriptName = 'AtlasImage.ps1'
$imageLog = 'c:\VagrantBox.txt'
cmd /c "exit 0"
# Write to standard out and file
function writeLog ($message) {
Write-Host "[$scriptName] $message"
Add-Content $imageLog "[$scriptName] $message"
}
# Use executeIgnoreExit to only trap exceptions, use executeExpression to trap all errors ($LASTEXITCODE is global)
function execute ($expression) {
$error.clear()
writeLog "[$(Get-date)] $expression"
try {
Invoke-Expression $expression
if(!$?) { writeLog "`$? = $?"; emailAndExit 1 }
} catch { Write-Output $_.Exception|format-list -force; emailAndExit 2 }
if ( $error[0] ) { writeLog "`$error[0] = $error"; emailAndExit 3 }
}
function executeExpression ($expression) {
execute $expression
if (( $LASTEXITCODE ) -and ( $LASTEXITCODE -ne 0 )) { writeLog "ERROR! Exiting with `$LASTEXITCODE = $LASTEXITCODE"; emailAndExit $LASTEXITCODE }
}
function executeIgnoreExit ($expression) {
execute $expression
if (( $LASTEXITCODE ) -and ( $LASTEXITCODE -ne 0 )) { writeLog "Warning `$LASTEXITCODE = $LASTEXITCODE"; cmd /c "exit 0" }
}
# Exception Handling email sending
function emailAndExit ($exitCode) {
if ($smtpServer) {
Send-MailMessage -To "$emailTo" -From "$emailFrom" -Subject "[$scriptName][$hypervisor] ERROR $exitCode" -SmtpServer "$smtpServer"
}
exit $exitCode
}
# Informational email notification
function emailProgress ($subject) {
if ($smtpServer) {
Send-MailMessage -To "$emailTo" -From "$emailFrom" -Subject "[$scriptName][$hypervisor] $subject" -SmtpServer "$smtpServer"
}
}
emailProgress "starting, logging to $imageLog"
writeLog "---------- start ----------"
if ($emailTo) {
Write-Host "[$scriptName] emailTo : $emailTo"
} else {
Write-Host "[$scriptName] emailTo : (not specified, email will not be attempted)"
}
if ($smtpServer) {
Write-Host "[$scriptName] smtpServer : $smtpServer"
} else {
Write-Host "[$scriptName] smtpServer : (not specified, email will not be attempted)"
}
if ($emailFrom) {
Write-Host "[$scriptName] emailFrom : $emailFrom"
} else {
Write-Host "[$scriptName] emailFrom : (not specified, email will not be attempted)"
}
if ($sysprep) {
writeLog "sysprep : $sysprep"
} else {
$sysprep = 'yes'
writeLog "sysprep : $sysprep (default)"
}
if ($stripDISM) {
writeLog "stripDISM : $stripDISM"
} else {
$stripDISM = 'no'
writeLog "stripDISM : $stripDISM (default)"
}
$systeminfo = systeminfo
if ( $systeminfo -match 'VirtualBox' ) {
$hypervisor = 'virtualbox'
} else {
$hypervisor = 'hyperv'
}
writeLog "hypervisor = $hypervisor"
if ( Test-Path $env:systemroot\SoftwareDistribution ) {
executeExpression "Remove-Item $env:systemroot\SoftwareDistribution -Recurse -Force"
}
executeExpression "cd $(split-path -parent $MyInvocation.MyCommand.Definition)"
executeExpression "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls11,Tls12'"
executeExpression "pwd"
if ( $hypervisor -eq 'virtualbox' ) {
$vbadd = '5.2.22'
writeLog "Install Guest Additions for $hypervisor, version $vbadd...`n"
executeExpression ".\automation\provisioning\mountImage.ps1 $env:userprofile\VBoxGuestAdditions_${vbadd}.iso http://download.virtualbox.org/virtualbox/${vbadd}/VBoxGuestAdditions_${vbadd}.iso"
$result = executeExpression "[Environment]::GetEnvironmentVariable(`'MOUNT_DRIVE_LETTER`', `'User`')"
emailProgress "Guest Additiions requires manual intervention ..."
executeExpression "`$proc = Start-Process -FilePath `"$result\VBoxWindowsAdditions-amd64.exe`" -ArgumentList `'/S`' -PassThru -Wait"
executeExpression ".\automation\provisioning\mountImage.ps1 $env:userprofile\VBoxGuestAdditions_${vbadd}.iso"
executeExpression "Remove-Item $env:userprofile\VBoxGuestAdditions_${vbadd}.iso"
} else {
writeLog "No client tools required for $hypervisor...`n"
}
if ( $stripDISM -eq 'yes' ) {
writeLog "Remove the features that are not required, then remove media for available features that are not installed"
executeExpression "@(`'Server-Media-Foundation`') | Remove-WindowsFeature"
executeExpression "Get-WindowsFeature | ? { `$_.InstallState -eq `'Available`' } | Uninstall-WindowsFeature -Remove"
} else {
writeLog "Strip DISM skipped (there is a bug in Windows Server 2016 where some disabled roles cannot be restored, e.g. ServerManager-Core-RSAT-Role-Tools"
}
writeLog "Deployment Image Servicing and Management (DISM.exe) clean-up"
executeIgnoreExit "Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase /Quiet"
writeLog "Windows Server Update service (WSUS) Clean-up"
executeExpression "Set-Service wuauserv -StartupType Disabled"
executeExpression "Stop-Service wuauserv"
executeExpression "Get-Service wuauserv | select -property name,status,starttype | Format-Table"
if ( Test-Path $env:systemroot\SoftwareDistribution ) {
executeExpression "Remove-Item $env:systemroot\SoftwareDistribution -Recurse -Force"
}
writeLog "Enable permissions to discard page file"
writeLog "`$System = GWMI Win32_ComputerSystem -EnableAllPrivileges"
$System = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges
executeExpression "`$System.AutomaticManagedPagefile = `$False"
writeLog "`$System.Put()"
$output = $System.Put()
writeLog "$output"
writeLog "Discard page file (is rebuilt at start-up)"
writeLog "`$CurrentPageFile = gwmi -query `"select * from Win32_PageFileSetting where name=`'c:\\pagefile.sys`'`""
$CurrentPageFile = Get-WmiObject -query "select * from Win32_PageFileSetting where name='c:\\pagefile.sys'"
executeExpression "`$CurrentPageFile.InitialSize = 512"
executeExpression "`$CurrentPageFile.MaximumSize = 512"
writeLog "`$CurrentPageFile.Put()"
$output = $CurrentPageFile.Put()
writeLog "$output"
writeLog "Prepare for Zeroing"
executeIgnoreExit "Optimize-Volume -DriveLetter C"
writeLog "See https://technet.microsoft.com/en-us/sysinternals/sdelete.aspx"
$zipFile = "SDelete.zip"
if (Test-Path "$zipFile") {
writeLog "$zipFile exists, skip download."
} else {
$url = "https://download.sysinternals.com/files/$zipFile"
executeExpression "(New-Object System.Net.WebClient).DownloadFile(`"$url`", `"$PWD\$zipFile`")"
}
$secureDeleteExe = "sdelete.exe"
if (Test-Path "$secureDeleteExe") {
writeLog "$secureDeleteExe exists, skip extraction."
} else {
executeExpression "Add-Type -AssemblyName System.IO.Compression.FileSystem"
executeExpression "[System.IO.Compression.ZipFile]::ExtractToDirectory(`"$PWD\$zipFile`", `"$PWD`")"
}
writeLog "See https://peter.hahndorf.eu/blog/WorkAroundSysinternalsLicenseP.html"
executeExpression "& reg.exe ADD `"HKCU\Software\Sysinternals\SDelete`" /v EulaAccepted /t REG_DWORD /d 1 /f"
writeLog "Zero unused disk"
executeExpression "./$secureDeleteExe -z c:"
if ($sysprep -eq 'yes') {
$scriptDir = "$env:windir\setup\scripts"
if (Test-Path "$scriptDir") {
writeLog "$scriptDir exists, skip create."
} else {
executeExpression "mkdir -Path $scriptDir"
}
writeLog "This script will be run once for sysprep'd machine https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-7/dd744268(v=ws.10)?redirectedfrom=MSDN"
$setupCommand = "$scriptDir\SetupComplete.cmd"
executeExpression "Set-Content $scriptDir\SetupComplete.cmd `'netsh advfirewall firewall set rule name=`"Windows Remote Management (HTTP-in)`" new action=allow`'"
executeExpression "Add-Content $scriptDir\SetupComplete.cmd `'reg add HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /d 0 /t REG_DWORD /f /reg:64`'"
executeExpression "Add-Content $scriptDir\SetupComplete.cmd `'cscript /Nologo slmgr.vbs /rearm`'"
executeExpression "cat $scriptDir\SetupComplete.cmd"
writeLog "$(cat $scriptDir\SetupComplete.cmd)"
writeLog "Close the WinRM port now, so Vagrant does not manage to connect during the system prep phase"
writeLog "$scriptDir\SetupComplete.cmd will reverse this once sysprep is complete"
executeExpression "netsh advfirewall firewall set rule name=`'Windows Remote Management (HTTP-in)`' new action=block"
$scriptDir = "C:\Windows\Panther\Unattend"
writeLog "Windows looks for unattended answer files in $scriptDir"
executeExpression "(New-Object System.Net.WebClient).DownloadFile(`'http://cdaf.io/static/app/downloads/unattend.xml`', `"$PWD\unattend.xml`")"
if (Test-Path "$scriptDir") {
writeLog "$scriptDir exists, skip create."
} else {
executeExpression "mkdir -Path $scriptDir"
}
$sysprepXML = "$scriptDir\unattend.xml"
if (Test-Path "$sysprepXML") {
writeLog "$sysprepXML exists, skip create."
} else {
executeExpression "Copy-Item $PWD\unattend.xml $scriptDir"
}
executeExpression "cat $scriptDir\unattend.xml"
emailProgress "last comms, starting sysprep"
executeExpression "& C:\windows\system32\sysprep\sysprep.exe /generalize /oobe /shutdown /unattend:$scriptDir\unattend.xml"
} else {
writeLog "sysprep = $sysprep, skipping unattended install and sysrep."
emailProgress "last comms, sysprep = $sysprep, skipping unattended install and sysrep."
executeExpression "shutdown /s /t 2"
}
writeLog "---------- stop ----------"
exit 0