-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathProgram.cs
More file actions
1156 lines (1061 loc) · 71.6 KB
/
Program.cs
File metadata and controls
1156 lines (1061 loc) · 71.6 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Xml;
using Schneegans.Unattend;
using System.IO;
using System.Text;
using System.Collections.Immutable;
using System.Reflection;
using UnattendGen.UserSettings;
using System.Diagnostics;
using Microsoft.VisualBasic;
namespace UnattendGen
{
internal class Program
{
static string GetCopyrightTimespan(int start, int current)
{
if (current <= start)
{
return current.ToString();
}
else
{
return $"{start.ToString()}-{current.ToString()}";
}
}
static string ValidateComputerName(string name)
{
if (string.IsNullOrWhiteSpace(name))
return "";
if (name.Length > 15)
return "";
if (name.ToCharArray().Any(char.IsWhiteSpace))
return "";
if (name.ToCharArray().All(char.IsAsciiDigit))
return "";
if (name.IndexOfAny(['{', '|', '}', '~', '[', '\\', ']', '^', '\'', ':', ';', '<', '=', '>', '?', '@', '!', '"', '#', '$', '%', '`', '(', ')', '+', '/', '.', ',', '*', '&']) > -1)
return "";
return name;
}
static void DebugWrite(string msg, bool debugMsg = false)
{
if (debugMsg)
Console.WriteLine($"DEBUG: {msg}");
}
static void ShowHelpMessage()
{
Console.WriteLine("=== PROGRAM HELP ===\n");
Console.WriteLine("USAGE\n\n" +
"\tUnattendGen [--target=<targetPath>] [--regionfile=<regionFile>] [--architecture={ x86 ; i386 | x64 ; amd64 | aarch64 ; arm64 },[...]] [--LabConfig] [--BypassNRO] [--ConfigSet] [--computername=<compName>] [--tzImplicit] [--partmode={ interactive | unattended | custom }] [--firmware | --generic | --customkey=<key>] [--msa] [--customusers] [--autologon={ firstadmin | builtinadmin }] [--b64obscure] [--pwExpire=<days>] [--lockout={ yes | no } [--vm={ vbox_gas | vmware | virtio | parallels }] [--wifi={ yes | no }] [--telem={ yes | no }] [--customscripts] [--hidewindows] [--restartexplorer] [--customcomponents]\n");
Console.WriteLine("SWITCHES\n\n" +
"\tGeneral switches:\n\n" +
"\t\t--help \t\tShows this help screen\n" +
"\t\t--target \t\tSaves the unattended answer file to the path specified by <targetPath>. Defaults to \"unattend.xml\" in the current directory if not set.\n\n" +
"\tRegional settings:\n\n" +
"\t\t--regionfile\t\tConfigures regional settings given a XML file specified by <regionFile>. Defaults to Interactive regional settings if not set.\n\n" +
"\tBasic system settings:\n\n" +
"\t\t--architecture\t\tConfigures the system architecture of the target answer file. Possible values: x86, i386 (Desktop 32-Bit); x64, amd64 (Desktop 64-Bit); aarch64, arm64 (Windows on ARM). Defaults to amd64 if not set. You can configure multiple architectures by separating them with commas (,)\n" +
"\t\t--LabConfig\t\tBypasses system requirement checks (Windows 11 only)\n" +
"\t\t--BypassNRO\t\tBypasses mandatory network connection setup (Windows 11 only, may not work on Windows 11 24H2)\n" +
"\t\t--ConfigSet\t\tConfigures the target system to use a configuration set or distribution share. Said set or share needs to be present in the ISO you copy the answer file to beforehand\n" +
"\t\t--computername\t\tSets a computer name defined by <compName>. Defaults to a random computer name if not set\n\n" +
"\tTime zone settings:\n\n" +
"\t\t--tzImplicit\t\tSets the system time zone to be determined from regional settings. Defaults to time zone settings from the regional settings file if not set\n\n" +
"\tDisk configuration settings:\n\n" +
"\t\t--partmode\t\tSets the partitioning mode. Possible values: interactive (ask during system setup); unattended (configure settings of Disk 0); custom (use a DiskPart script). Defaults to interactive if not set\n\n" +
"\tEdition settings: (USE ONE SWITCH BUT NOT ALL)\n\n" +
"\t\t--firmware\t\tConfigures the target system to use the product key embedded in the firmware (note, this requires a modern system)\n" +
"\t\t--generic\t\tSets generic edition settings using a configuration file. Defaults to Pro edition if not set\n" +
"\t\t--customkey\t\tSets a custom key, defined by <key> to be used for installation, which may or may not be valid\n\n" +
"\tUser settings:\n\n" +
"\t\t--msa \t\tConfigures the target system to ask for a Microsoft account. No additional user account parameters need to be passed, or the system will not ask for the online account\n" +
"\t\t--customusers\t\tConfigures the users of the target system with a \"userAccounts.xml\" configuration file. Defaults to an interactive setup if not specified\n" +
"\t\t--autologon\t\tConfigures user automatic log-on settings. Possible values: firstadmin (first admin in account list); builtinadmin (built-in Windows admin account). Defaults to disabled auto log-on if not set\n" +
"\t\t--b64obscure\t\tObscures passwords with Base64\n" +
"\t\t--pwExpire\t\tConfigures password expiration settings (not recommended by NIST) given the value defined in <days>. Defaults to no password expiration if not set\n" +
"\t\t--lockout\t\tConfigures account lockout settings. Possible values: yes (enable settings determined by a config file); no (disable settings - NOT RECOMMENDED)\n\n" +
"\tVirtual Machine Support:\n\n" +
"\t\t--vm \t\tConfigures virtual machine support. Possible values: vbox_gas (VirtualBox Guest Additions); vmware (VMware Tools); virtio (VirtIO Guest Tools); parallels (Parallels Tools). Defaults to no VM support if not set\n\n" +
"\tWireless settings:\n\n" +
"\t\t--wifi \t\tConfigures wireless networking for the target system. Possible values: yes (configure settings with a wireless configuration file); no (skip configuration). Defaults to interactive if not set\n\n" +
"\tSystem telemetry:\n\n" +
"\t\t--telem \t\tConfigures system telemetry. Possible values: yes (enable telemetry); no (disable telemetry). Defaults to interactive if not set\n\n" +
"\tPost-installation scripts:\n\n" +
"\t\t--customscripts\t\tConfigures post-installation scripts using a \"scripts.xml\" configuration file\n" +
"\t\t--hidewindows\t\tHides any post-installation script windows (don't do this unless you are not debugging your scripts)\n" +
"\t\t--restartexplorer\tRestarts File Explorer after running post-installation scripts\n\n" +
"\tCustom configuration:\n\n" +
"\t\t--customcomponents\tConfigures custom components for your unattended answer file using XML configuration files");
}
static async Task Main(string[] args)
{
bool debugMode = false;
string targetPath = "";
bool regionInteractive = true;
string regionFile = "";
RegionFile region = new RegionFile();
RegionFile defaultRegion = new RegionFile();
defaultRegion.regionLang.Add(new ImageLanguages("en-US", "English (United States)"));
defaultRegion.regionLocales.Add(new UserLocales("en-US", "English (United States)", "0409", "00000409", "244"));
defaultRegion.regionKeys.Add(new KeyboardIdentifiers("00000409", "US", "Keyboard"));
defaultRegion.regionGeo.Add(new GeoIds("244", "United States"));
defaultRegion.regionTimes.Add(new TimeOffsets("UTC", "(UTC) Coordinated Universal Time"));
region = defaultRegion;
string computerName = "";
AnswerFileGenerator.PartitionSettingsMode partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
bool genericChosen = true;
SystemEdition defaultEdition = new SystemEdition("pro", "Pro", "VK7JG-NPHTM-C97JM-9MPGT-3V66T");
bool accountsInteractive = true;
AutoLogon defaultLogonSettings = new AutoLogon(AutoLogon.AutoLogonMode.None, "");
AutoLogon logonSettings = new AutoLogon();
logonSettings = defaultLogonSettings;
AccountLockout defaultlockout = new AccountLockout(true, 10, 10, 10);
AccountLockout lockout = new AccountLockout();
lockout = defaultlockout;
AnswerFileGenerator.VirtualMachineSolution vm = AnswerFileGenerator.VirtualMachineSolution.No;
bool wirelessInteractive = true;
bool wirelessSkip = false;
WirelessNetwork wirelessNetwork = new WirelessNetwork();
AnswerFileGenerator.SystemTelemetry telemetry = AnswerFileGenerator.SystemTelemetry.Interactive;
List<SystemComponent> defaultComponents = new List<SystemComponent>();
// Add Microsoft-Windows-Shell-Setup in oobeSystem pass. It's already filled in, but add it anyway
List<SystemPass> defaultPasses = new List<SystemPass>();
defaultPasses.Add(new SystemPass("oobeSystem"));
SystemComponent defaultComponent = new SystemComponent("Microsoft-Windows-Shell-Setup", defaultPasses, "");
defaultComponents.Add(defaultComponent);
List<Schneegans.Unattend.ProcessorArchitecture> defaultArchitectures = new List<Schneegans.Unattend.ProcessorArchitecture>();
defaultArchitectures.Add(Schneegans.Unattend.ProcessorArchitecture.amd64);
bool noSensitiveFiles = false;
Console.WriteLine($"UnattendGen{(File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DT")) ? " for DISMTools" : "")}, version {Assembly.GetEntryAssembly().GetName().Version.ToString()}");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine($"Program: (c) {GetCopyrightTimespan(2024, DateTime.Today.Year)}. CodingWonders Software\nLibrary: (c) {GetCopyrightTimespan(2024, DateTime.Today.Year)}. Christoph Schneegans");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("SEE ATTACHED PROGRAM LICENSES FOR MORE INFORMATION REGARDING USE AND REDISTRIBUTION\n");
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "showversions")))
{
try
{
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UnattendGenerator.dll"));
string[] prodVersionParts = fvi.ProductVersion.Split('+'); // split version and git commit sha
Console.WriteLine($"- Library Version: {prodVersionParts[0]}");
Console.WriteLine($"- Git Commit: {prodVersionParts[1]}");
Console.WriteLine($" https://github.com/cschneegans/unattend-generator/commit/{prodVersionParts[1]}\n");
}
catch
{
// Don't show it
}
}
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX) &&
System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.X64)
{
// After macOS Tahoe, Apple will stop making Intel releases of macOS. Better inform the user
Console.WriteLine("After macOS Tahoe (macOS 26), Apple will stop making Intel builds of macOS. UnattendGen will stop working on your system when a new .NET release either stops supporting Intel releases or stops supporting macOS Tahoe. For now, it will continue working.\n");
}
var generator = new AnswerFileGenerator();
if (Environment.GetCommandLineArgs().Contains("--debug"))
debugMode = true;
if (Environment.GetCommandLineArgs().Length >= 2)
{
foreach (string cmdLine in Environment.GetCommandLineArgs())
{
if (cmdLine == "--help")
{
ShowHelpMessage();
return;
}
else if (cmdLine.StartsWith("--target", StringComparison.OrdinalIgnoreCase))
{
targetPath = cmdLine.Replace("--target=", "").Trim();
}
else if (cmdLine.StartsWith("--regionfile", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Region file specified. Reading settings...");
regionInteractive = false;
regionFile = cmdLine.Replace("--regionfile=", "").Trim();
if (regionFile != "" && File.Exists(regionFile))
{
try
{
region.regionLang = ImageLanguages.LoadItems(regionFile);
region.regionGeo = GeoIds.LoadItems(regionFile);
region.regionLocales = UserLocales.LoadItems(regionFile);
region.regionKeys = KeyboardIdentifiers.LoadItems(regionFile);
region.regionTimes = TimeOffsets.LoadItems(regionFile);
DebugWrite($"Regional Settings:\n\n\t- Image Language: {region.regionLang[0].Id}\n\t- Locale: {region.regionLocales[0].Id}\n\t- Keyboard: {region.regionKeys[0].Id}\n\t- Geo ID: {region.regionGeo[0].Id}\n\t- Time Offset: {region.regionTimes[0].Id}\n", (debugMode | Debugger.IsAttached));
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse regional settings file. Continuing with Interactive...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
region = defaultRegion;
regionInteractive = true;
}
}
else
{
Console.WriteLine("WARNING: Regional settings file does not exist. Continuing with Interactive...");
regionInteractive = true;
}
}
else if (cmdLine.StartsWith("--architecture", StringComparison.OrdinalIgnoreCase))
{
string[] architectures = cmdLine.Replace("--architecture=", "").Trim().Split(',');
if (architectures.Length > 0)
{
// For each architecture that we have detected, check if it is valid and add it to the list in the generator
foreach (string arch in architectures)
{
switch (arch.Trim())
{
case "x86":
case "i386":
generator.processorArchitectures.Add(Schneegans.Unattend.ProcessorArchitecture.x86);
DebugWrite("Specified architecture: x86", (debugMode | Debugger.IsAttached));
break;
case "x64":
case "amd64":
generator.processorArchitectures.Add(Schneegans.Unattend.ProcessorArchitecture.amd64);
DebugWrite("Specified architecture: amd64", (debugMode | Debugger.IsAttached));
break;
case "aarch64":
case "arm64":
generator.processorArchitectures.Add(Schneegans.Unattend.ProcessorArchitecture.arm64);
DebugWrite("Specified architecture: arm64", (debugMode | Debugger.IsAttached));
break;
default:
Console.WriteLine($"WARNING: Unknown processor architecture: {arch.Trim()}. Continuing with AMD64...");
generator.processorArchitectures.Add(Schneegans.Unattend.ProcessorArchitecture.amd64);
break;
}
}
}
}
else if (cmdLine.StartsWith("--LabConfig", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("LabConfig: True", (debugMode | Debugger.IsAttached));
generator.SV_LabConfig = true;
}
else if (cmdLine.StartsWith("--BypassNRO", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("BypassNRO: True", (debugMode | Debugger.IsAttached));
Console.WriteLine($"INFO: BypassNRO setting will be configured. You will be able to use the target file only on Windows 11. Do note that this setting may not work for you on Windows 11 24H2.");
generator.SV_BypassNRO = true;
}
else if (cmdLine.StartsWith("--ConfigSet", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("Windows SIM Configuration Set: True", (debugMode | Debugger.IsAttached));
generator.UseConfigSet = true;
}
else if (cmdLine.StartsWith("--computername", StringComparison.OrdinalIgnoreCase))
{
string name = cmdLine.Replace("--computername=", "").Trim();
if (!name.StartsWith("script:", StringComparison.OrdinalIgnoreCase))
{
name = ValidateComputerName(name);
if (name == "")
Console.WriteLine($"WARNING: Computer name \"{cmdLine.Replace("--computername=", "").Trim()}\" is not valid. Continuing with a random computer name...");
DebugWrite($"Computer name: {name}", (debugMode | Debugger.IsAttached));
}
else
{
DebugWrite($"Computer name will be provided by a PowerShell script", (debugMode | Debugger.IsAttached));
}
computerName = name;
}
else if (cmdLine.StartsWith("--tzImplicit", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("Time Zone is now implicit (determine from Regional Settings - See Respective Settings For More Info!!!)", (debugMode | Debugger.IsAttached));
generator.timeZoneImplicit = true;
}
else if (cmdLine.StartsWith("--partmode", StringComparison.OrdinalIgnoreCase))
{
switch (cmdLine.Replace("--partmode=", "").Trim())
{
case "interactive":
partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
break;
case "unattended":
Console.WriteLine("INFO: Selected partition mode is unattended. Reading settings...");
partition = AnswerFileGenerator.PartitionSettingsMode.Unattended;
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unattPartSettings.xml")))
{
try
{
DiskZeroSettings? diskZero = DiskZeroSettings.LoadDiskSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unattPartSettings.xml"));
generator.diskZeroSettings = diskZero;
DebugWrite($"Disk 0 settings:\n\n\t- Partition Style: {diskZero.partStyle.ToString()}\n\t- Install Recovery Environment? {(diskZero.recoveryEnvironment != DiskZeroSettings.RecoveryEnvironmentMode.None ? $"Yes\n\t\t- Location: {diskZero.recoveryEnvironment.ToString()}\n\t{(diskZero.partStyle == DiskZeroSettings.PartitionStyle.GPT ? $"- EFI System Partition Size: {diskZero.ESPSize} MB\n\t" : "")}" : "No")}- Recovery Partition Size: {diskZero.recEnvSize} MB\n", (debugMode | Debugger.IsAttached));
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse partition settings file. Continuing with Interactive...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
}
}
else
{
Console.WriteLine("WARNING: Partition settings file does not exist. Continuing with Interactive...");
partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
}
break;
case "custom":
Console.WriteLine("INFO: Selected partition mode is custom (use DiskPart script). Reading settings...");
partition = AnswerFileGenerator.PartitionSettingsMode.Custom;
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DiskPartSettings.xml")))
{
try
{
DiskPartSettings? diskPart = DiskPartSettings.LoadDiskSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DiskPartSettings.xml"));
generator.diskPartSettings = diskPart;
DebugWrite($"DiskPart settings:\n\n\t- Script file: \"{diskPart.scriptFile}\". Contents:\n\n\t\t{File.ReadAllText(diskPart.scriptFile).Replace("\n", "\n\t\t").Trim()}\n\n\t- Automatic configuration? {(diskPart.automaticInstall ? "Yes" : $"No\n\t\t- Disk: {diskPart.diskNum}\n\t\t- Partition: {diskPart.partNum}")}\n", (debugMode | Debugger.IsAttached));
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse partition settings file. Continuing with Interactive...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
}
}
else
{
Console.WriteLine("WARNING: Partition settings file does not exist. Continuing with Interactive...");
partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
}
break;
default:
Console.WriteLine($"WARNING: Unknown partition mode: {cmdLine.Replace("--partmode=", "").Trim()}. Continuing with Interactive...");
partition = AnswerFileGenerator.PartitionSettingsMode.Interactive;
break;
}
}
else if (cmdLine.StartsWith("--firmware", StringComparison.OrdinalIgnoreCase))
{
generator.editionFirmwareChosen = true;
genericChosen = false;
DebugWrite("The unattended answer file will use the product key embedded in the firmware", (debugMode | Debugger.IsAttached));
}
else if (cmdLine.StartsWith("--generic", StringComparison.OrdinalIgnoreCase))
{
generator.genericEdition = defaultEdition;
Console.WriteLine("INFO: The unattended answer file will use a generic product key. Reading edition configuration...");
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "edition.xml")))
{
try
{
SystemEdition edition = SystemEdition.LoadSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "edition.xml"));
generator.genericEdition = edition;
DebugWrite($"Edition settings:\n\n\t- Edition ID: {edition.Id}\n\t- Edition name: {edition.DisplayName}\n\t- Product key: {edition.ProductKey}\n", (debugMode | Debugger.IsAttached));
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse edition settings file. Continuing with default Pro edition...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
generator.genericEdition = defaultEdition;
}
}
else
{
Console.WriteLine("WARNING: Edition settings file does not exist. Continuing with default Pro edition...");
generator.genericEdition = defaultEdition;
}
}
else if (cmdLine.StartsWith("--customkey", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: The unattended answer file will not use a generic product key");
genericChosen = false;
string key = cmdLine.Replace("--customkey=", "").Trim();
DebugWrite($"Edition settings:\n\n\t- Product key: {key}\n", (debugMode | Debugger.IsAttached));
generator.customKey = key;
}
else if (cmdLine.StartsWith("--msa", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("The system will ask you for a Microsoft account. 24H2 does not present ways to bypass this with bypassnro, unless you join a domain", (debugMode | Debugger.IsAttached));
generator.msaInteractive = true;
}
else if (cmdLine.StartsWith("--customusers", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Manual user configuration will be used. Reading user list...");
accountsInteractive = false;
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "userAccounts.xml")))
{
try
{
List<UserAccount> accounts = UserAccount.LoadAccounts(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "userAccounts.xml"));
generator.accounts = accounts;
DebugWrite($"User accounts:\n", (debugMode | Debugger.IsAttached));
if (debugMode | Debugger.IsAttached)
{
if (accounts.Count > 0)
{
foreach (UserAccount account in accounts)
{
Console.WriteLine($"\t- User {accounts.IndexOf(account) + 1}:");
Console.WriteLine($"\t\t- Enabled? {(account.Enabled ? "Yes" : "No")}");
if (account.Enabled)
{
Console.WriteLine($"\t\t- Name: {account.Name}");
Console.WriteLine($"\t\t- Display Name: {account.DisplayName}");
Console.WriteLine($"\t\t- Password: {account.Password}");
Console.WriteLine($"\t\t- Group: {account.Group switch
{
UserAccount.UserGroup.Administrators => "Administrators",
UserAccount.UserGroup.Users => "Users",
_ => "Users"
}}");
}
}
Console.WriteLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse user accounts file. Continuing with Interactive Settings...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
accountsInteractive = true;
}
}
else
{
Console.WriteLine("WARNING: User accounts file does not exist. Continuing with Interactive Settings...");
accountsInteractive = true;
}
}
else if (cmdLine.StartsWith("--autologon", StringComparison.OrdinalIgnoreCase))
{
if (!accountsInteractive)
{
Console.WriteLine("INFO: Configuring auto-logon settings...");
switch (cmdLine.Replace("--autologon=", "").Trim())
{
case "firstadmin":
DebugWrite("Setting auto-logon to first admin...", (debugMode | Debugger.IsAttached));
logonSettings.logonMode = AutoLogon.AutoLogonMode.FirstAdmin;
if (generator.accounts.Count > 0)
{
foreach (UserAccount account in generator.accounts)
{
if (account.Group == UserAccount.UserGroup.Administrators)
{
DebugWrite($"First Admin in Accounts list: {account.Name}", (debugMode | Debugger.IsAttached));
break;
}
}
}
break;
case "builtinadmin":
DebugWrite("Setting auto-logon to Windows admin...", (debugMode | Debugger.IsAttached));
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "autoLogon.xml")))
{
try
{
logonSettings.winAdminPass = AutoLogon.GetAdminPassword(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "autoLogon.xml"));
logonSettings.logonMode = AutoLogon.AutoLogonMode.BuiltInAdmin;
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse auto-logon settings file. Disabling auto-logon...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
logonSettings.logonMode = AutoLogon.AutoLogonMode.None;
}
}
else
{
Console.WriteLine("WARNING: Auto-logon settings file does not exist. Disabling auto-logon...");
logonSettings.logonMode = AutoLogon.AutoLogonMode.None;
}
break;
}
}
else
{
Console.WriteLine("INFO: Auto-logon settings will not be configured since you need to configure accounts during Setup. Please pass the \"--customusers\" flag after providing a user data file with the name of \"userAccounts.xml\" to be able to configure these settings");
}
}
else if (cmdLine.StartsWith("--b64obscure", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("User passwords will be obscured with Base64", (debugMode | Debugger.IsAttached));
generator.Base64Obscure = true;
}
else if (cmdLine.StartsWith("--pwExpire", StringComparison.OrdinalIgnoreCase))
{
try
{
Console.WriteLine("INFO: Configuring password expiration settings...");
generator.ExpirationDays = Convert.ToInt32(cmdLine.Replace("--pwExpire=", "").Trim());
DebugWrite($"Password expiration: {generator.ExpirationDays} day(s)", (debugMode | Debugger.IsAttached));
}
catch
{
generator.ExpirationDays = 0;
}
}
else if (cmdLine.StartsWith("--lockout", StringComparison.OrdinalIgnoreCase))
{
switch (cmdLine.Replace("--lockout=", "").Trim())
{
case "yes":
Console.WriteLine("INFO: Enforcing Account Lockout policy...");
lockout.Enabled = true;
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lockout.xml")))
{
Console.WriteLine("INFO: Lockout policy file detected. Reading settings...");
try
{
lockout = AccountLockout.GetAccountLockout(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lockout.xml"));
DebugWrite($"Account Lockout Settings:\n\n\tAfter {lockout.FailedAttempts} attempt(s) within {lockout.TimeFrame} minute(s), unlock accounts automatically after {lockout.AutoUnlock} minute(s)\n", (debugMode | Debugger.IsAttached));
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse Account Lockout settings file. Continuing with default options...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
lockout = defaultlockout;
}
}
break;
case "no":
Console.WriteLine("INFO: Disabling Account Lockout policy. User accounts may be easier to penetrate into with brute-force attacks");
lockout.Enabled = false;
break;
default:
break;
}
}
else if (cmdLine.StartsWith("--vm", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Configuring Virtual Machine Support...");
switch (cmdLine.Replace("--vm=", "").Trim())
{
case "vbox_gas":
DebugWrite("VM Solution: VirtualBox Guest Additions", (debugMode | Debugger.IsAttached));
vm = AnswerFileGenerator.VirtualMachineSolution.VBox_GAs;
break;
case "vmware":
DebugWrite("VM Solution: VMware Tools", (debugMode | Debugger.IsAttached));
vm = AnswerFileGenerator.VirtualMachineSolution.VMware_Tools;
break;
case "virtio":
DebugWrite("VM Solution: VirtIO Guest Tools", (debugMode | Debugger.IsAttached));
vm = AnswerFileGenerator.VirtualMachineSolution.VirtIO;
break;
case "parallels":
DebugWrite("VM Solution: Parallels", (debugMode | Debugger.IsAttached));
vm = AnswerFileGenerator.VirtualMachineSolution.Parallels;
break;
default:
Console.WriteLine($"WARNING: Unknown VM solution: {cmdLine.Replace("--vm=", "").Trim()}. Continuing without VM support...");
break;
}
}
else if (cmdLine.StartsWith("--wifi", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Configuring Wireless Networks...");
switch (cmdLine.Replace("--wifi=", "").Trim())
{
case "yes":
Console.WriteLine("INFO: Wireless settings will be configured. Reading configuration file...");
wirelessInteractive = false;
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wireless.xml")))
{
try
{
WirelessNetwork wireless = WirelessNetwork.LoadSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wireless.xml"));
wirelessNetwork = wireless;
DebugWrite($"Wireless settings:\n", (debugMode | Debugger.IsAttached));
if (debugMode | Debugger.IsAttached)
{
Console.WriteLine($"\t- SSID: {wireless.SSID}");
Console.WriteLine($"\t- Password: {new string('*', wireless.Password.Length)} (hidden for your security)");
Console.WriteLine($"\t- Authentication mode: {wireless.Authentication switch
{
WirelessNetwork.AuthenticationProtocol.Open => "Open (most vulnerable)",
WirelessNetwork.AuthenticationProtocol.WPA2 => "WPA2-PSK",
WirelessNetwork.AuthenticationProtocol.WPA3 => "WPA3-SAE",
_ => "WPA2-PSK"
}}");
Console.WriteLine($"\t- Connect even if not broadcasting? {(wireless.NonBroadcast ? "Yes" : "No")}");
Console.WriteLine();
}
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse wireless settings file. Continuing with Interactive Settings...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
wirelessInteractive = true;
}
}
else
{
Console.WriteLine("WARNING: Wireless settings file does not exist. Continuing with Interactive Settings...");
wirelessInteractive = true;
}
break;
case "no":
wirelessSkip = true;
break;
}
}
else if (cmdLine.StartsWith("--telem", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Configuring system telemetry settings...");
switch (cmdLine.Replace("--telem=", "").Trim())
{
case "yes":
DebugWrite("Enabling system telemetry...", (debugMode | Debugger.IsAttached));
telemetry = AnswerFileGenerator.SystemTelemetry.Yes;
break;
case "no":
DebugWrite("(Attempting to) disable system telemetry...", (debugMode | Debugger.IsAttached));
telemetry = AnswerFileGenerator.SystemTelemetry.No;
break;
default:
Console.WriteLine($"WARNING: Unknown telemetry configuration: {cmdLine.Replace("--telem=", "").Trim()}. Continuing with Interactive settings...");
telemetry = AnswerFileGenerator.SystemTelemetry.Interactive;
break;
}
}
else if (cmdLine.StartsWith("--customscripts", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Configuring post-installation scripts...");
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scripts.xml")))
{
try
{
List<PostInstallScript> scripts = PostInstallScript.LoadScripts(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scripts.xml"));
generator.PostInstallScripts = scripts;
DebugWrite($"Post-installation scripts:\n", (debugMode | Debugger.IsAttached));
if (debugMode | Debugger.IsAttached)
{
if (scripts.Count > 0)
{
foreach (PostInstallScript script in scripts)
{
Console.WriteLine("--- Post-installation script:\n");
Console.WriteLine($"- Contents: \n\n\t{script.ScriptContent.Replace("\n", "\n\t").Trim()}\n");
if (script.Extension != PostInstallScript.ScriptExtension.NoFile)
{
Console.WriteLine($"- Script Type: {script.Extension switch
{
PostInstallScript.ScriptExtension.PowerShell => "PowerShell (.PS1)",
PostInstallScript.ScriptExtension.Batch => "Batch (.BAT, .CMD, .NT)",
PostInstallScript.ScriptExtension.Reg => "Windows Registry",
_ => "Unknown"
}}");
}
Console.WriteLine($"- When to apply: {script.Stage switch
{
PostInstallScript.StageContext.System => "during system setup",
PostInstallScript.StageContext.FirstLogon => "when the first user logs on",
PostInstallScript.StageContext.FirstTimeUserLogon => "when a user logs on for the first time",
PostInstallScript.StageContext.NTUserHiveModify => "during system setup - this modifies NTUSER.DAT",
_ => "Invalid entry"
}}");
Console.WriteLine();
}
}
Console.WriteLine();
}
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse post-installation scripts file. Continuing without settings...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
generator.PostInstallScripts = new List<PostInstallScript>();
}
}
else
{
generator.PostInstallScripts = new List<PostInstallScript>();
}
}
else if (cmdLine.StartsWith("--hidewindows", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("Script windows will be hidden", (debugMode | Debugger.IsAttached));
generator.HideScriptWindows = true;
}
else if (cmdLine.StartsWith("--restartexplorer", StringComparison.OrdinalIgnoreCase))
{
DebugWrite("File Explorer will be restarted after running post-installation scripts...", (debugMode | Debugger.IsAttached));
generator.RestartExplorer = true;
}
else if (cmdLine.StartsWith("--customcomponents", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: Configuring custom components...");
try
{
List<SystemComponent> components = SystemComponent.LoadComponents();
generator.SystemComponents = components;
DebugWrite($"System components:\n", (debugMode | Debugger.IsAttached));
if (debugMode | Debugger.IsAttached)
{
if (components.Count > 0)
{
foreach (SystemComponent component in components)
{
Console.WriteLine($"\t- Component name: {component.Id}");
Console.WriteLine($"\t- Pass: {component.Passes[0].Name}");
Console.WriteLine($"\t- Data: \n\n{component.Data}\n\n");
}
}
Console.WriteLine();
}
}
catch (Exception ex)
{
Console.WriteLine("WARNING: Could not parse system components file. Continuing without settings...");
if (Debugger.IsAttached)
Debugger.Break();
DebugWrite($"Error Message - {ex.Message}", (debugMode | Debugger.IsAttached));
generator.SystemComponents = defaultComponents;
}
}
else if (cmdLine.StartsWith("--nosensitivefiles", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("INFO: removing sensitive files after installation");
noSensitiveFiles = true;
}
if (cmdLine != Assembly.GetExecutingAssembly().Location)
DebugWrite($"Successfully parsed command-line switch {cmdLine}", (debugMode | Debugger.IsAttached));
}
}
generator.regionalInteractive = regionInteractive;
generator.regionalSettings = region;
generator.randomComputerName = (computerName == "");
generator.computerName = computerName;
generator.accountsInteractive = accountsInteractive;
generator.partitionSettings = partition;
generator.editionGenericChosen = genericChosen;
generator.autoLogonSettings = logonSettings;
generator.lockout = lockout;
generator.virtualMachine = vm;
generator.WirelessInteractive = wirelessInteractive;
generator.WirelessSkip = wirelessSkip;
generator.WirelessSettings = wirelessNetwork;
generator.Telemetry = telemetry;
if (generator.genericEdition is null)
{
Console.WriteLine("WARNING: No edition settings have been specified. Continuing with the default Pro edition...");
generator.genericEdition = defaultEdition;
}
if (generator.accounts is null)
{
Console.WriteLine("WARNING: No users have been specified. Continuing with Interactive settings...");
generator.accountsInteractive = true;
}
if ((generator.processorArchitectures is null) || (generator.processorArchitectures.Count <= 0))
{
Console.WriteLine("WARNING: No architectures have been specified. Continuing with default architectures...");
generator.processorArchitectures = defaultArchitectures;
}
generator.noSensitiveFiles = noSensitiveFiles;
await generator.GenerateAnswerFile(targetPath != "" ? targetPath : "unattend.xml");
}
}
public class AnswerFileGenerator
{
public enum PartitionSettingsMode
{
Interactive,
Unattended,
Custom
}
public enum VirtualMachineSolution
{
No,
VBox_GAs,
VMware_Tools,
VirtIO,
Parallels
}
public enum SystemTelemetry
{
Interactive,
No,
Yes
}
public bool regionalInteractive;
public RegionFile regionalSettings = new RegionFile();
public bool randomComputerName;
public string computerName = "";
public List<Schneegans.Unattend.ProcessorArchitecture> processorArchitectures = [];
public bool SV_LabConfig;
public bool SV_BypassNRO;
public bool UseConfigSet;
public bool timeZoneImplicit;
public PartitionSettingsMode partitionSettings;
public DiskZeroSettings? diskZeroSettings;
public DiskPartSettings? diskPartSettings;
public bool editionFirmwareChosen;
public bool editionGenericChosen;
public SystemEdition? genericEdition;
public string? customKey;
public bool accountsInteractive;
public bool msaInteractive;
public List<UserAccount>? accounts;
public AutoLogon? autoLogonSettings;
public bool Base64Obscure;
public int ExpirationDays = 0;
public AccountLockout? lockout;
public VirtualMachineSolution virtualMachine;
public bool WirelessInteractive;
public bool WirelessSkip;
public WirelessNetwork? WirelessSettings;
public SystemTelemetry Telemetry;
public List<PostInstallScript>? PostInstallScripts = new List<PostInstallScript>();
public bool HideScriptWindows;
public bool RestartExplorer;
public List<SystemComponent>? SystemComponents = new List<SystemComponent>();
public bool noSensitiveFiles;
public async Task GenerateAnswerFile(string targetPath)
{
await Task.Run(() =>
{
try
{
ImmutableList<Account> userAccounts = ImmutableList<Account>.Empty;
List<Account> accountList = new List<Account>();
if (null != accounts && accounts.Count > 0)
{
foreach (UserAccount account in accounts)
{
if (!account.Enabled)
continue;
accountList.Add(new Account(
name: account.Name,
displayName: "",
password: account.Password,
group: account.Group switch
{
UserAccount.UserGroup.Administrators => "Administrators",
UserAccount.UserGroup.Users => "Users",
_ => "Users"
}));
}
}
userAccounts = userAccounts.AddRange(accountList.ToArray());
ImmutableHashSet<Schneegans.Unattend.ProcessorArchitecture> architectures = ImmutableHashSet<Schneegans.Unattend.ProcessorArchitecture>.Empty;
architectures = architectures.Union(processorArchitectures);
//var componentDictionary = ImmutableDictionary.Create<string, ImmutableSortedSet<Pass>>();
var componentDictionary = ImmutableDictionary.Create<ComponentAndPass, string>();
foreach (SystemComponent component in SystemComponents)
{
var passSet = ImmutableSortedSet.CreateBuilder<Pass>();
foreach (SystemPass componentPass in component.Passes)
{
componentDictionary = componentDictionary.Add(new ComponentAndPass(component.Id, componentPass.Name switch
{
"offlineServicing" => Pass.offlineServicing,
"windowsPE" => Pass.windowsPE,
"generalize" => Pass.generalize,
"specialize" => Pass.specialize,
"auditSystem" => Pass.auditSystem,
"auditUser" => Pass.auditUser,
"oobeSystem" => Pass.oobeSystem,
_ => Pass.oobeSystem // Default to oobeSystem. This is the most unlikely case
}), component.Data);
}
}
Script[] scripts = [];
if (PostInstallScripts.Count > 0)
{
List<Script> scriptList = new List<Script>();
foreach (PostInstallScript script in PostInstallScripts)
{
scriptList.Add(
new Script(
script.ScriptContent, script.Stage switch
{
PostInstallScript.StageContext.System => ScriptPhase.System,
PostInstallScript.StageContext.FirstLogon => ScriptPhase.FirstLogon,
PostInstallScript.StageContext.FirstTimeUserLogon => ScriptPhase.UserOnce,
PostInstallScript.StageContext.NTUserHiveModify => ScriptPhase.DefaultUser,
_ => ScriptPhase.System
},
script.Extension switch
{
PostInstallScript.ScriptExtension.PowerShell => ScriptType.Ps1,
PostInstallScript.ScriptExtension.Batch => ScriptType.Cmd,
PostInstallScript.ScriptExtension.Reg => ScriptType.Reg,
PostInstallScript.ScriptExtension.VBScript => ScriptType.Vbs,
PostInstallScript.ScriptExtension.JScript => ScriptType.Js,
_ => ScriptType.Ps1
}));
}
scripts = scriptList.ToArray();
}
UnattendGenerator generator = new();
XmlDocument xml = generator.GenerateXml(
Configuration.Default with
{
LanguageSettings = regionalInteractive ? new InteractiveLanguageSettings() : new UnattendedLanguageSettings(