-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeploy.ps1
More file actions
406 lines (342 loc) · 15 KB
/
deploy.ps1
File metadata and controls
406 lines (342 loc) · 15 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Threading;
public class TrustedInstaller
{
const uint SC_MANAGER_CONNECT = 0x1;
const uint SERVICE_QUERY_STATUS = 0x4;
const uint SERVICE_START = 0x10;
const uint PROCESS_ALL_ACCESS = 0x1F0FFF;
const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
const uint CREATE_NO_WINDOW = 0x08000000;
const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
const int STARTF_USESHOWWINDOW = 0x00000001;
const short SW_HIDE = 0;
const uint TOKEN_ADJUST_PRIVILEGES = 0x20;
const uint TOKEN_ADJUST_SESSIONID = 0x100;
const uint TOKEN_QUERY = 0x8;
const uint SE_PRIVILEGE_ENABLED = 0x2;
[StructLayout(LayoutKind.Sequential)]
struct LUID { public uint LowPart; public int HighPart; }
[StructLayout(LayoutKind.Sequential)]
struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_PRIVILEGES
{
public uint PrivilegeCount;
public LUID_AND_ATTRIBUTES Privileges;
}
static readonly string[] AllPrivileges = {
"SeAssignPrimaryTokenPrivilege","SeLockMemoryPrivilege","SeIncreaseQuotaPrivilege",
"SeTcbPrivilege","SeSecurityPrivilege","SeTakeOwnershipPrivilege","SeLoadDriverPrivilege",
"SeSystemProfilePrivilege","SeSystemtimePrivilege","SeProfileSingleProcessPrivilege",
"SeIncreaseBasePriorityPrivilege","SeCreatePagefilePrivilege","SeCreatePermanentPrivilege",
"SeBackupPrivilege","SeRestorePrivilege","SeShutdownPrivilege","SeDebugPrivilege",
"SeAuditPrivilege","SeSystemEnvironmentPrivilege","SeChangeNotifyPrivilege","SeUndockPrivilege",
"SeManageVolumePrivilege","SeImpersonatePrivilege","SeCreateGlobalPrivilege",
"SeIncreaseWorkingSetPrivilege","SeTimeZonePrivilege","SeCreateSymbolicLinkPrivilege",
"SeDelegateSessionUserImpersonatePrivilege"
};
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool OpenProcessToken(IntPtr h, uint a, out IntPtr t);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LookupPrivilegeValue(string s, string n, out LUID l);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool AdjustTokenPrivileges(
IntPtr t, bool d, ref TOKEN_PRIVILEGES n, int l, IntPtr p, IntPtr r);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr OpenSCManager(string m, string d, uint a);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr OpenService(IntPtr scm, string name, uint access);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool QueryServiceStatusEx(
IntPtr h, int i, out SERVICE_STATUS_PROCESS s, int sz, out int b);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool StartService(IntPtr h, int a, IntPtr v);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(uint a, bool i, int p);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool InitializeProcThreadAttributeList(
IntPtr l, int c, int f, ref IntPtr s);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool UpdateProcThreadAttribute(
IntPtr l, uint f, IntPtr a, IntPtr v, IntPtr s, IntPtr p, IntPtr r);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CreateProcessW(
string a, string c, IntPtr p1, IntPtr p2, bool i, uint f,
IntPtr e, string d, ref STARTUPINFOEX s, out PROCESS_INFORMATION p);
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
const uint INFINITE = 0xFFFFFFFF;
static void EnableAllPrivileges(IntPtr hProcess)
{
IntPtr hTok;
if (!OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_ADJUST_SESSIONID, out hTok))
return;
foreach (string p in AllPrivileges)
{
LUID luid;
if (!LookupPrivilegeValue(null, p, out luid))
continue;
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
tp.PrivilegeCount = 1;
tp.Privileges.Luid = luid;
tp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hTok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
}
}
public static void Spawn(string commandLine)
{
var scm = OpenSCManager(null, null, SC_MANAGER_CONNECT);
var svc = OpenService(scm, "TrustedInstaller", SERVICE_START | SERVICE_QUERY_STATUS);
SERVICE_STATUS_PROCESS ssp;
int bytesNeeded;
do
{
QueryServiceStatusEx(
svc, 0, out ssp,
Marshal.SizeOf(typeof(SERVICE_STATUS_PROCESS)),
out bytesNeeded);
if (ssp.dwCurrentState == 1)
StartService(svc, 0, IntPtr.Zero);
}
while (ssp.dwCurrentState != 4);
IntPtr hTI = OpenProcess(PROCESS_ALL_ACCESS, false, ssp.dwProcessId);
IntPtr size = IntPtr.Zero;
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
IntPtr list = Marshal.AllocHGlobal(size);
InitializeProcThreadAttributeList(list, 1, 0, ref size);
IntPtr parent = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(parent, hTI);
UpdateProcThreadAttribute(
list, 0,
(IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
parent, (IntPtr)IntPtr.Size,
IntPtr.Zero, IntPtr.Zero);
STARTUPINFOEX si = new STARTUPINFOEX();
si.StartupInfo.cb = Marshal.SizeOf(typeof(STARTUPINFOEX));
si.StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
si.StartupInfo.wShowWindow = SW_HIDE;
si.lpAttributeList = list;
PROCESS_INFORMATION pi;
CreateProcessW(
null,
commandLine,
IntPtr.Zero, IntPtr.Zero,
false,
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW,
IntPtr.Zero, null,
ref si, out pi);
EnableAllPrivileges(pi.hProcess);
WaitForSingleObject(pi.hProcess, INFINITE);
}
struct SERVICE_STATUS_PROCESS
{
public int dwServiceType, dwCurrentState, dwControlsAccepted;
public int dwWin32ExitCode, dwServiceSpecificExitCode;
public int dwCheckPoint, dwWaitHint, dwProcessId, dwServiceFlags;
}
struct PROCESS_INFORMATION
{
public IntPtr hProcess, hThread;
public int dwProcessId, dwThreadId;
}
struct STARTUPINFO
{
public int cb;
public IntPtr lpReserved, lpDesktop, lpTitle;
public int dwX, dwY, dwXSize, dwYSize;
public int dwXCountChars, dwYCountChars;
public int dwFillAttribute, dwFlags;
public short wShowWindow, cbReserved2;
public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
}
struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
}
"@
$admin = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $admin.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "This script must be run as Administrator."
return
}
if (-not [Environment]::Is64BitProcess) {
Write-Host "This script must be run in 64-bit PowerShell."
exit 1
}
$VirtualDriveEnum = Get-PnpDevice -FriendlyName 'Microsoft Virtual Drive Enumerator' -ErrorAction SilentlyContinue
if ($VirtualDriveEnum -and $VirtualDriveEnum.Status -ne 'OK') {
$VirtualDriveEnum | Enable-PnpDevice -Confirm:$False | Out-Null
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\vdrvroot" -Name "Start" -Value 0
Write-Host "Restart your PC and rerun this script."
exit 1
}
Write-Host "Please select the Windows ISO..."
$IsoPicker = New-Object System.Windows.Forms.OpenFileDialog
$IsoPicker.Filter = "ISO Files (*.iso)|*.iso"
$IsoPicker.Title = "Select the Windows ISO file"
$IsoPicker.Multiselect = $false
if ($IsoPicker.ShowDialog() -ne [System.Windows.Forms.DialogResult]::OK) {
Write-Host "No ISO selected. Exiting."
return
}
$InstallDrivers = Read-Host "Do you want to install drivers? (y/n)"
if ($InstallDrivers -match '^[Yy]') {
Write-Host "Please select your drivers folder..."
$DriverPicker = New-Object System.Windows.Forms.FolderBrowserDialog
$DriverPicker.Description = "Select the drivers folder"
if ($DriverPicker.ShowDialog() -ne [System.Windows.Forms.DialogResult]::OK) { return }
$DriversDir = $DriverPicker.SelectedPath
}
Write-Host "`n===== Step 1: Check Partition Style =====`n"
$DiskNumber = (Get-Partition -DriveLetter C | Get-Disk).Number
if ((Get-Partition -DriveLetter "C" | Get-Disk).PartitionStyle -eq 'MBR') {
Write-Host "Partition style is MBR. Converting to GPT..."
mbr2gpt /convert /disk:$DiskNumber /allowFullOS
Write-Host "Please set Boot Mode to UEFI in BIOS after conversion, then rerun this script."
return
} else {
Write-Host "Partition style is GPT"
}
Write-Host "`n===== Step 2: Check BitLocker State =====`n"
try {
if ((Get-BitLockerVolume -MountPoint C:).VolumeStatus -eq "FullyEncrypted") {
Write-Host "BitLocker is enabled. Disabling..."
Disable-BitLocker -MountPoint C:
Write-Host "Wait until decryption finishes, then rerun this script."
return
} else {
Write-Host "BitLocker is disabled"
}
} catch {
Write-Host "BitLocker is disabled"
}
Write-Host "`n===== Step 3: Check Partitions =====`n"
$Partitions = Get-Partition -DiskNumber $DiskNumber | Where-Object { $_.Type -eq 'Basic' -and $_.Size -gt 0 }
$ShrinkTargetsMB = @(1048576, 524288, 262144, 131072, 65536)
$ShrinkablePartition = $null
$ShrinkAmountMB = 0
$ExistingPartition = $null
$TargetDrive = $null
$ExistingPartitions = @()
foreach ($p in $Partitions) {
try {
$items = @(Get-ChildItem "$($p.DriveLetter):\" -Force)
$userItems = $items | Where-Object { $_.Name -notin @('System Volume Information', '$RECYCLE.BIN', 'desktop.ini') }
if ($userItems.Count -eq 0) {
$ExistingPartitions += $p
}
} catch { }
}
if ($ExistingPartitions.Count -gt 0) {
$ExistingPartition = $ExistingPartitions | Sort-Object { (Get-Volume -DriveLetter $_.DriveLetter).SizeRemaining } -Descending | Select-Object -First 1
$TargetDrive = $ExistingPartition.DriveLetter + ":"
$FreeGB = [math]::Round((Get-Volume -DriveLetter $ExistingPartition.DriveLetter).SizeRemaining / 1GB, 2)
Write-Host "Using empty partition $TargetDrive with $FreeGB GB free"
}
else {
foreach ($Partition in $Partitions) {
if (-not $Partition.DriveLetter) { continue }
$Supported = Get-PartitionSupportedSize -DriveLetter $Partition.DriveLetter
$MaxShrinkMB = [math]::Floor(($Partition.Size - $Supported.SizeMin) / 1MB)
Write-Host "Partition $($Partition.DriveLetter): $MaxShrinkMB MB shrinkable"
$Partition | Add-Member -NotePropertyName MaxShrinkMB -NotePropertyValue $MaxShrinkMB
}
foreach ($Partition in $Partitions) {
foreach ($Target in $ShrinkTargetsMB) {
if ($Partition.MaxShrinkMB -ge $Target) {
$ShrinkablePartition = $Partition
$ShrinkAmountMB = $Target
break
}
}
if ($ShrinkablePartition) { break }
}
if ($ShrinkablePartition) {
Write-Host "Shrinking partition $($ShrinkablePartition.DriveLetter): by $ShrinkAmountMB MB..."
$NewSize = $ShrinkablePartition.Size - ($ShrinkAmountMB * 1MB)
Resize-Partition -DriveLetter $ShrinkablePartition.DriveLetter -Size $NewSize
$NewPartition = New-Partition -DiskNumber $DiskNumber -UseMaximumSize -AssignDriveLetter
$TargetDrive = "$($NewPartition.DriveLetter):"
}
else {
Write-Host "No partition with at least 64GB of free space or shrinkable space found. Use the 'Split' function in Minitool Partition Wizard Free and rerun this script."
Write-Host "Press Enter to exit..."
if ($Host.Name -eq 'ConsoleHost') {
[void][System.Console]::ReadLine()
}
return
}
}
Write-Host "`n===== Step 4: Prepare Target Partition =====`n"
Write-Host "Formatting partition $TargetDrive..."
Start-Process -FilePath "cmd.exe" -ArgumentList "/c ""format $TargetDrive /fs:ntfs /q /y /v:AutoOS > nul 2> nul""" -NoNewWindow -Wait
Write-Host "`n===== Step 5: Apply Windows Image =====`n"
try {
Write-Host "Mounting ISO..."
$MountedIso = (Mount-DiskImage -ImagePath $IsoPicker.FileName -PassThru | Get-Volume).DriveLetter + ":"
Write-Host "Copying install.wim..."
$TempWim = "$env:TEMP\install.wim"
Copy-Item -Path "$MountedIso\sources\install.wim" -Destination $TempWim -Force
attrib -r $TempWim
} finally {
Write-Host "Unmounting ISO..."
Dismount-DiskImage -ImagePath $IsoPicker.FileName | Out-Null
}
Write-Host "Mounting install.wim..."
$MountDirectory = "C:\mnt"
New-Item -Path $MountDirectory -ItemType Directory -Force | Out-Null
$Images = Get-WindowsImage -ImagePath $TempWim
foreach ($Image in $Images) {
try {
Mount-WindowsImage -Path $MountDirectory -ImagePath $TempWim -Name $Image.ImageName | Out-Null
Write-Host "Stripping 8.3 filenames..."
[TrustedInstaller]::Spawn(
"cmd /c fsutil 8dot3name strip /f /s `"$MountDirectory`""
)
} finally {
Write-Host "Unmounting install.wim..."
Dismount-WindowsImage -Path $MountDirectory -Save | Out-Null
[TrustedInstaller]::Spawn(
"cmd /c rmdir /s /q `"$MountDirectory`""
)
}
}
Write-Host "Applying Windows image to $TargetDrive..."
DISM /Apply-Image /ImageFile:$TempWim /Index:1 /ApplyDir:$TargetDrive
Remove-Item $TempWim -Force
Write-Host "`n===== Step 6: Install Drivers =====`n"
if ($InstallDrivers -match '^[Yy]') {
Write-Host "Installing drivers from $DriversDir..."
DISM /Image:$TargetDrive /Add-Driver /Driver:$DriversDir /Recurse
}
else {
Write-Host "Skipping driver installation..."
}
Write-Host "`n===== Step 7: Add unattend.xml =====`n"
Write-Host "Adding unattend.xml..."
New-Item -ItemType Directory -Path $TargetDrive\Windows\Panther -Force | Out-Null
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/tinodin/AutoOS/master/unattend.xml" -OutFile $TargetDrive\Windows\Panther\unattend.xml
Write-Host "`n===== Step 8: Create Boot Entry =====`n"
Write-Host "Creating boot entry..."
bcdedit /set "{current}" bootmenupolicy legacy
bcdboot $TargetDrive\Windows
bcdedit /set "{default}" description "AutoOS"
bcdedit /set "{default}" bootmenupolicy legacy
bcdedit /timeout 6
Write-Host "`n===== AutoOS Deployment Completed Successfully! ====="
Write-Host "Press Enter to exit..."
if ($Host.Name -eq 'ConsoleHost') {
[void][System.Console]::ReadLine()
return
}