forked from cschneegans/unattend-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.cs
906 lines (787 loc) · 25.1 KB
/
Main.cs
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
namespace Schneegans.Unattend;
public enum Pass
{
offlineServicing,
windowsPE,
generalize,
specialize,
auditSystem,
auditUser,
oobeSystem
}
public enum RecoveryMode
{
None, Folder, Partition
}
public enum PartitionLayout
{
MBR, GPT
}
public enum ProcessorArchitecture
{
x86, amd64, arm64
}
public enum ExpressSettingsMode
{
Interactive, EnableAll, DisableAll
}
public enum TaskbarSearchMode
{
Hide = 0,
Icon = 1,
Box = 2
}
abstract class CommandConfig
{
public readonly static CommandConfig WindowsPE = new WindowsPECommandConfig();
public readonly static CommandConfig Specialize = new SpecializeCommandConfig();
public readonly static CommandConfig Oobe = new OobeCommandConfig();
public abstract XmlElement CreateElement(XmlDocument doc, XmlNamespaceManager ns);
/// <summary>
/// Inserts a command using this markup:
/// <code>
/// <settings pass="windowsPE">
/// <component name="Microsoft-Windows-Setup">
/// <RunSynchronous>
/// <RunSynchronousCommand>
/// <Path>
/// </code>
/// </summary>
private class WindowsPECommandConfig : CommandConfig
{
public override XmlElement CreateElement(XmlDocument doc, XmlNamespaceManager ns)
{
var container = Util.GetOrCreateElement(Pass.windowsPE, "Microsoft-Windows-Setup", "RunSynchronous", doc, ns);
var outer = Util.NewElement("RunSynchronousCommand", container, doc, ns);
return Util.NewElement("Path", outer, doc, ns);
}
}
/// <summary>
/// Inserts a command using this markup:
/// <code>
/// <settings pass="specialize">
/// <component name="Microsoft-Windows-Deployment">
/// <RunSynchronous>
/// <RunSynchronousCommand>
/// <Path>
/// </code>
/// </summary>
private class SpecializeCommandConfig : CommandConfig
{
public override XmlElement CreateElement(XmlDocument doc, XmlNamespaceManager ns)
{
var container = Util.GetOrCreateElement(Pass.specialize, "Microsoft-Windows-Deployment", "RunSynchronous", doc, ns);
var outer = Util.NewElement("RunSynchronousCommand", container, doc, ns);
return Util.NewElement("Path", outer, doc, ns);
}
}
/// <summary>
/// Inserts a command using this markup:
/// <code>
/// <settings pass="oobeSystem">
/// <component name="Microsoft-Windows-Shell-Setup">
/// <FirstLogonCommands>
/// <SynchronousCommand>
/// <CommandLine>
/// </code>
/// </summary>
private class OobeCommandConfig : CommandConfig
{
public override XmlElement CreateElement(XmlDocument doc, XmlNamespaceManager ns)
{
var container = Util.GetOrCreateElement(Pass.oobeSystem, "Microsoft-Windows-Shell-Setup", "FirstLogonCommands", doc, ns);
var outer = Util.NewElement("SynchronousCommand", container, doc, ns);
return Util.NewElement("CommandLine", outer, doc, ns);
}
}
}
class CommandAppender(XmlDocument doc, XmlNamespaceManager ns, CommandConfig config)
{
public void Append(string value)
{
config.CreateElement(doc, ns).InnerText = value;
}
public void Append(IEnumerable<string> values)
{
foreach (string value in values)
{
Append(value);
}
}
}
static class CommandBuilder
{
public static string Raw(string command)
{
return command;
}
public static string ShellCommand(string command)
{
return $@"cmd.exe /c ""{command}""";
}
/// <summary>
/// Runs a command and redirects its <c>stdout</c> and <c>stderr</c> to a file.
/// </summary>
public static string ShellCommand(string command, string outFile)
{
return $@"cmd.exe /c ""{command} >>""{outFile}"" 2>&1""";
}
public static string RegistryCommand(string value)
{
return $"reg.exe {value}";
}
public static string UserRunOnceCommand(string rootKey, string subKey, string name, string command)
{
return UserRunCommand(rootKey, subKey, "RunOnce", name, command);
}
public static string RunAtLogonCommand(string rootKey, string subKey, string name, string command)
{
return UserRunCommand(rootKey, subKey, "Run", name, command);
}
private static string UserRunCommand(string rootKey, string subKey, string runKey, string name, string command)
{
static string Escape(string s)
{
return s.Replace(@"""", @"\""");
}
return RegistryCommand(@$"add ""{rootKey}\{subKey}\Software\Microsoft\Windows\CurrentVersion\{runKey}"" /v ""{Escape(name)}"" /t REG_SZ /d ""{Escape(command)}"" /f");
}
public delegate IEnumerable<string> RegistryDefaultUserAction(string rootKey, string subKey);
public static IEnumerable<string> RegistryDefaultUserCommand(RegistryDefaultUserAction action)
{
string rootKey = "HKU";
string subKey = "DefaultUser";
IEnumerable<string> content = action.Invoke(rootKey, subKey);
if (content.Any())
{
return [
RegistryCommand(@$"load ""{rootKey}\{subKey}"" ""C:\Users\Default\NTUSER.DAT"""),
.. content,
RegistryCommand(@$"unload ""{rootKey}\{subKey}"""),
];
}
else
{
return [];
}
}
public static string PowerShellCommand(string value)
{
{
const char quote = '"';
if (value.Contains(quote))
{
throw new ArgumentException($"PowerShell command '{value}' must not contain '{quote}'.");
}
}
{
const char semicolon = ';';
const char brace = '}';
if (!value.EndsWith(semicolon) && !value.EndsWith(brace))
{
throw new ArgumentException($"PowerShell command '{value}' must end with either '{semicolon}' or '{brace}'.");
}
}
return @$"powershell.exe -NoProfile -Command ""{value}""";
}
public static string InvokePowerShellScript(string filepath)
{
return PowerShellCommand($"Get-Content -LiteralPath '{filepath}' -Raw | Invoke-Expression;");
}
public static string InvokeVBScript(string filepath)
{
return @$"cscript.exe //E:vbscript ""{filepath}""";
}
public static string InvokeJScript(string filepath)
{
return @$"cscript.exe //E:jscript ""{filepath}""";
}
public static IEnumerable<string> WriteToFile(string path, string line)
{
static string EscapeShell(string command)
{
return command
.Replace("^", "^^")
.Replace("&", "^&")
.Replace("<", "^<")
.Replace(">", "^>")
.Replace("|", "^|")
.Replace("%", "^%");
}
if (string.IsNullOrWhiteSpace(line))
{
yield break;
}
string command = $@"cmd.exe /c "">>""{path}"" echo {EscapeShell(line)}""";
if (command.Length >= 255)
{
throw new ConfigurationException($"Line '{line}' is too long.");
}
yield return command;
}
}
public class ConfigurationException(string? message) : Exception(message);
public record class Configuration(
ILanguageSettings LanguageSettings,
IAccountSettings AccountSettings,
IPartitionSettings PartitionSettings,
IEditionSettings EditionSettings,
ILockoutSettings LockoutSettings,
IPasswordExpirationSettings PasswordExpirationSettings,
IProcessAuditSettings ProcessAuditSettings,
IComputerNameSettings ComputerNameSettings,
ITimeZoneSettings TimeZoneSettings,
IWifiSettings WifiSettings,
IWdacSettings WdacSettings,
ImmutableHashSet<ProcessorArchitecture> ProcessorArchitectures,
ImmutableDictionary<string, ImmutableSortedSet<Pass>> Components,
ImmutableList<Bloatware> Bloatwares,
ExpressSettingsMode ExpressSettings,
ScriptSettings ScriptSettings,
IKeySettings KeySettings,
IWallpaperSettings WallpaperSettings,
bool BypassRequirementsCheck,
bool BypassNetworkCheck,
bool EnableLongPaths,
bool EnableRemoteDesktop,
bool HardenSystemDriveAcl,
bool AllowPowerShellScripts,
bool DisableLastAccess,
bool NoAutoRebootWithLoggedOnUsers,
bool DisableDefender,
bool DisableSac,
bool DisableUac,
bool DisableSmartScreen,
bool DisableSystemRestore,
bool DisableFastStartup,
bool TurnOffSystemSounds,
bool DisableAppSuggestions,
bool DisableWidgets,
bool VBoxGuestAdditions,
bool VMwareTools,
bool VirtIoGuestTools,
bool PreventDeviceEncryption,
bool ClassicContextMenu,
bool LeftTaskbar,
bool DeleteTaskbarIcons,
bool ShowFileExtensions,
bool ShowAllTrayIcons,
HideModes HideFiles,
bool HideEdgeFre,
bool MakeEdgeUninstallable,
TaskbarSearchMode TaskbarSearch,
IStartPinsSettings StartPinsSettings,
IStartTilesSettings StartTilesSettings
)
{
public static Configuration Default => new(
LanguageSettings: new InteractiveLanguageSettings(),
AccountSettings: new InteractiveAccountSettings(),
PartitionSettings: new InteractivePartitionSettings(),
EditionSettings: new InteractiveEditionSettings(),
LockoutSettings: new DefaultLockoutSettings(),
PasswordExpirationSettings: new DefaultPasswordExpirationSettings(),
ProcessAuditSettings: new DisabledProcessAuditSettings(),
ComputerNameSettings: new RandomComputerNameSettings(),
TimeZoneSettings: new ImplicitTimeZoneSettings(),
WifiSettings: new InteractiveWifiSettings(),
WdacSettings: new SkipWdacSettings(),
ProcessorArchitectures: [ProcessorArchitecture.amd64],
Components: ImmutableDictionary.Create<string, ImmutableSortedSet<Pass>>(),
Bloatwares: [],
ExpressSettings: ExpressSettingsMode.DisableAll,
ScriptSettings: new ScriptSettings([]),
KeySettings: new SkipKeySettings(),
WallpaperSettings: new DefaultWallpaperSettings(),
BypassRequirementsCheck: false,
BypassNetworkCheck: false,
EnableLongPaths: false,
EnableRemoteDesktop: false,
HardenSystemDriveAcl: false,
AllowPowerShellScripts: false,
DisableLastAccess: false,
NoAutoRebootWithLoggedOnUsers: false,
DisableDefender: false,
DisableSac: false,
DisableUac: false,
DisableSmartScreen: false,
DisableFastStartup: false,
DisableSystemRestore: false,
TurnOffSystemSounds: false,
DisableAppSuggestions: false,
DisableWidgets: false,
VBoxGuestAdditions: false,
VMwareTools: false,
VirtIoGuestTools: false,
PreventDeviceEncryption: false,
ClassicContextMenu: false,
LeftTaskbar: false,
DeleteTaskbarIcons: false,
ShowFileExtensions: false,
ShowAllTrayIcons: false,
HideFiles: HideModes.Hidden,
HideEdgeFre: false,
MakeEdgeUninstallable: false,
TaskbarSearch: TaskbarSearchMode.Box,
StartPinsSettings: new DefaultStartPinsSettings(),
StartTilesSettings: new DefaultStartTilesSettings()
);
}
public interface IKeyed
{
string Id { get; }
}
public abstract class BloatwareStep(
string[] appliesTo
)
{
public ImmutableSortedSet<string> AppliesTo { get; } = ImmutableSortedSet.CreateRange(appliesTo);
}
public class SelectorBloatwareStep(
string[] appliesTo,
string selector
) : BloatwareStep(appliesTo)
{
public string Selector { get; } = selector;
}
public class PackageBloatwareStep(
string[] appliesTo,
string selector
) : SelectorBloatwareStep(appliesTo, selector);
public class CapabilityBloatwareStep(
string[] appliesTo,
string selector
) : SelectorBloatwareStep(appliesTo, selector);
public class OptionalFeatureBloatwareStep(
string[] appliesTo,
string selector
) : SelectorBloatwareStep(appliesTo, selector);
public class CustomBloatwareStep(
string[] appliesTo
) : BloatwareStep(appliesTo);
public class Bloatware(
string displayName,
string? token,
ImmutableList<BloatwareStep> steps
) : IKeyed
{
public string DisplayName { get; } = displayName;
public string Id { get; } = $"Remove{token ?? displayName.Replace(" ", "")}";
public ImmutableList<BloatwareStep> Steps { get; } = steps;
[JsonIgnore]
public string? StepsLabel
{
get
{
IEnumerable<string> strings = Steps.SelectMany<BloatwareStep, string>(s => s switch
{
SelectorBloatwareStep sel => [sel.Selector],
CustomBloatwareStep => [],
_ => throw new NotImplementedException(),
}
);
return strings.Any() ? string.Join(", ", strings) : null;
}
}
}
public class Component(
string id,
ImmutableSortedSet<Pass> passes
) : IKeyed
{
public string Id { get; } = Validate(id);
private static readonly Regex Pattern = new("^[a-z-]+$", RegexOptions.IgnoreCase);
private static string Validate(string id)
{
if (!Pattern.IsMatch(id))
{
throw new ArgumentException($"ID '{id}' contains illegal characters.", nameof(id));
}
return id;
}
public ImmutableSortedSet<Pass> Passes { get; } = passes;
public string Uri
{
get
{
string name = Id switch
{
"Microsoft-Windows-WDF-KernelLibrary" => "microsoft-windows-wdf-kernel-library",
"Microsoft-Windows-MapControl-Desktop" => "microsoft-windows-mapcontrol",
_ => Id.ToLowerInvariant(),
};
return $"https://learn.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/{name}";
}
}
}
public class WindowsEdition(
string id,
string displayName,
string productKey,
bool visible
) : IKeyed
{
public string Id { get; } = id;
public string DisplayName { get; } = displayName;
public string ProductKey { get; } = productKey;
public bool Visible = visible;
}
public class ImageLanguage(
string id,
string displayName
) : IKeyed
{
public string Id { get; } = id;
public string DisplayName { get; } = displayName;
}
public enum InputType
{
Keyboard, IME
}
public class KeyboardIdentifier(
string id,
string displayName,
InputType type
) : IKeyed
{
public string Id { get; } = id;
public string DisplayName { get; } = displayName;
public InputType Type { get; } = type;
}
public class TimeOffset(
string id,
string displayName
) : IKeyed
{
public string Id { get; } = id;
public string DisplayName { get; } = displayName;
}
public class GeoLocation(
string id,
string displayName
) : IKeyed
{
public string Id { get; } = id;
public string DisplayName { get; } = displayName;
}
public class KeyboardConverter(
UnattendGenerator generator
) : JsonConverter<KeyboardIdentifier>
{
public override bool CanWrite => false;
public override KeyboardIdentifier? ReadJson(JsonReader reader, Type objectType, KeyboardIdentifier? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return reader.TokenType switch
{
JsonToken.String => generator.Lookup<KeyboardIdentifier>("" + reader.Value),
JsonToken.Null => null,
_ => throw new NotSupportedException(),
};
}
public override void WriteJson(JsonWriter writer, KeyboardIdentifier? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class GeoLocationConverter(
UnattendGenerator generator
) : JsonConverter<GeoLocation>
{
public override bool CanWrite => false;
public override GeoLocation? ReadJson(JsonReader reader, Type objectType, GeoLocation? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return reader.TokenType switch
{
JsonToken.String => generator.Lookup<GeoLocation>("" + reader.Value),
JsonToken.Null => null,
_ => throw new NotSupportedException(),
};
}
public override void WriteJson(JsonWriter writer, GeoLocation? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class UserLocale(
string id,
string displayName,
KeyboardIdentifier? keyboardLayout,
string lcid,
GeoLocation? geoLocation
) : IKeyed
{
public string Id { get; } = id;
public string DisplayName { get; } = displayName;
public string LCID { get; } = lcid;
public KeyboardIdentifier? KeyboardLayout { get; } = keyboardLayout;
public GeoLocation? GeoLocation { get; } = geoLocation;
}
public static class Constants
{
public const string UsersGroup = "Users";
public const string AdministratorsGroup = "Administrators";
public const string DefaultPassword = "password";
public const int RecoveryPartitionSize = 1000;
public const int EspDefaultSize = 300;
public static readonly string DiskpartScript = DiskModifier.GetCustomDiskpartScript();
public const string MyNamespaceUri = "https://schneegans.de/windows/unattend-generator/";
}
public class UnattendGenerator
{
public UnattendGenerator()
{
{
string json = Util.StringFromResource("Bloatware.json");
JsonSerializerSettings settings = new()
{
TypeNameHandling = TypeNameHandling.Auto,
};
Bloatwares = JsonConvert.DeserializeObject<Bloatware[]>(json, settings).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("Component.json");
Components = JsonConvert.DeserializeObject<Component[]>(json).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("ImageLanguage.json");
ImageLanguages = JsonConvert.DeserializeObject<ImageLanguage[]>(json).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("KeyboardIdentifier.json");
KeyboardIdentifiers = JsonConvert.DeserializeObject<KeyboardIdentifier[]>(json).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("GeoId.json");
GeoLocations = JsonConvert.DeserializeObject<GeoLocation[]>(json).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("UserLocale.json");
JsonConverter[] converters = [new KeyboardConverter(this), new GeoLocationConverter(this)];
UserLocales = JsonConvert.DeserializeObject<UserLocale[]>(json, converters).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("WindowsEdition.json");
WindowsEditions = JsonConvert.DeserializeObject<WindowsEdition[]>(json).ToKeyedDictionary();
}
{
string json = Util.StringFromResource("TimeOffset.json");
TimeOffsets = JsonConvert.DeserializeObject<TimeOffset[]>(json).ToKeyedDictionary();
}
{
VerifyUniqueKeys(Components.Values, e => e.Id);
}
{
VerifyUniqueKeys(WindowsEditions.Values, e => e.Id);
VerifyUniqueKeys(WindowsEditions.Values, e => e.DisplayName);
VerifyUniqueKeys(WindowsEditions.Values, e => e.ProductKey);
}
{
VerifyUniqueKeys(UserLocales.Values, e => e.Id);
VerifyUniqueKeys(UserLocales.Values, e => e.DisplayName);
}
{
VerifyUniqueKeys(KeyboardIdentifiers.Values, e => e.Id);
VerifyUniqueKeys(KeyboardIdentifiers.Values, e => e.DisplayName);
}
{
VerifyUniqueKeys(ImageLanguages.Values, e => e.Id);
VerifyUniqueKeys(ImageLanguages.Values, e => e.DisplayName);
}
{
VerifyUniqueKeys(TimeOffsets.Values, e => e.Id);
VerifyUniqueKeys(TimeOffsets.Values, e => e.DisplayName);
}
}
private static void VerifyUniqueKeys<T>(IEnumerable<T> items, Func<T, object> keySelector)
{
items.GroupBy(keySelector).ToList().ForEach(group =>
{
if (group.Count() != 1)
{
throw new ArgumentException($"'{group.Key}' occurs more than once.");
}
});
}
public ExplicitTimeZoneSettings CreateExplicitTimeZoneSettings(string id)
{
return new ExplicitTimeZoneSettings(
TimeZone: Lookup<TimeOffset>(id)
);
}
public IImmutableDictionary<string, TimeOffset> TimeOffsets { get; }
public IImmutableDictionary<string, GeoLocation> GeoLocations { get; }
public IImmutableDictionary<string, Component> Components { get; }
public IImmutableDictionary<string, Bloatware> Bloatwares { get; }
public IImmutableDictionary<string, KeyboardIdentifier> KeyboardIdentifiers { get; }
public IImmutableDictionary<string, UserLocale> UserLocales { get; }
public IImmutableDictionary<string, ImageLanguage> ImageLanguages { get; }
public IImmutableDictionary<string, WindowsEdition> WindowsEditions { get; }
[return: NotNull]
private static T Lookup<T>(IImmutableDictionary<string, T> dic, string key) where T : IKeyed
{
if (dic.TryGetValue(key, out T? value))
{
return value;
}
else
{
throw new ConfigurationException($"Could not find an element of type '{nameof(T)}' with key '{key}'.");
}
}
[return: NotNull]
public T Lookup<T>(string key) where T : class, IKeyed
{
if (typeof(T) == typeof(WindowsEdition))
{
return (T)(object)Lookup(WindowsEditions, key);
}
if (typeof(T) == typeof(UserLocale))
{
return (T)(object)Lookup(UserLocales, key);
}
if (typeof(T) == typeof(ImageLanguage))
{
return (T)(object)Lookup(ImageLanguages, key);
}
if (typeof(T) == typeof(KeyboardIdentifier))
{
return (T)(object)Lookup(KeyboardIdentifiers, key);
}
if (typeof(T) == typeof(TimeOffset))
{
return (T)(object)Lookup(TimeOffsets, key);
}
if (typeof(T) == typeof(Bloatware))
{
return (T)(object)Lookup(Bloatwares, key);
}
if (typeof(T) == typeof(GeoLocation))
{
return (T)(object)Lookup(GeoLocations, key);
}
throw new NotSupportedException();
}
public XmlDocument GenerateXml(Configuration config)
{
var doc = Util.XmlDocumentFromResource("autounattend.xml");
var ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("u", "urn:schemas-microsoft-com:unattend");
ns.AddNamespace("wcm", "http://schemas.microsoft.com/WMIConfig/2002/State");
ns.AddNamespace("s", Constants.MyNamespaceUri);
ModifierContext context = new(
Configuration: config,
Document: doc,
NamespaceManager: ns,
Generator: this
);
new List<Modifier> {
new DiskModifier(context),
new BypassModifier(context),
new ProductKeyModifier(context),
new UsersModifier(context),
new BloatwareModifier(context),
new LocalesModifier(context),
new ExpressSettingsModifier(context),
new WifiModifier(context),
new EmptyElementsModifier(context),
new LockoutModifier(context),
new PasswordExpirationModifier(context),
new OptimizationsModifier(context),
new ComponentsModifier(context),
new ComputerNameModifier(context),
new TimeZoneModifier(context),
new WdacModifier(context),
new ScriptModifier(context),
new OrderModifier(context),
new ProcessorArchitectureModifier(context),
new PrettyModifier(context),
}.ForEach(modifier =>
{
modifier.Process();
});
Util.ValidateAgainstSchema(doc, "autounattend.xsd");
return doc;
}
public byte[] GenerateBytes(Configuration config)
{
return Util.ToPrettyBytes(GenerateXml(config));
}
}
public record class ModifierContext(
XmlDocument Document,
XmlNamespaceManager NamespaceManager,
Configuration Configuration,
UnattendGenerator Generator
);
abstract class Modifier(ModifierContext context)
{
public XmlDocument Document { get; } = context.Document;
public XmlNamespaceManager NamespaceManager { get; } = context.NamespaceManager;
public Configuration Configuration { get; } = context.Configuration;
public UnattendGenerator Generator { get; } = context.Generator;
public XmlElement NewSimpleElement(string name, XmlElement parent, string innerText)
{
return Util.NewSimpleElement(name, parent, innerText, Document, NamespaceManager);
}
public XmlElement NewElement(string name, XmlElement parent)
{
return Util.NewElement(name, parent, Document, NamespaceManager);
}
public abstract void Process();
public CommandAppender GetAppender(CommandConfig config)
{
return new CommandAppender(Document, NamespaceManager, config);
}
public void AddXmlFile(XmlDocument xml, string path)
{
AddFile(Util.ToPrettyString(xml), useCDataSection: true, path);
}
public void AddTextFile(string content, string path)
{
AddFile(content, useCDataSection: false, path);
}
private void AddFile(string content, bool useCDataSection, string path)
{
{
XmlNode root = Document.SelectSingleNodeOrThrow("/u:unattend", NamespaceManager);
XmlNode? extensions = root.SelectSingleNode("s:Extensions", NamespaceManager);
if (extensions == null)
{
extensions = Document.CreateElement("Extensions", Constants.MyNamespaceUri);
root.AppendChild(extensions);
XmlNode extractScript = Document.CreateElement("ExtractScript", Constants.MyNamespaceUri);
extensions.AppendChild(extractScript);
extractScript.AppendChild(
Document.CreateTextNode(
Util.Indent(
Util.StringFromResource("ExtractScripts.ps1")
)
)
);
CommandAppender appender = GetAppender(CommandConfig.Specialize);
appender.Append(
CommandBuilder.PowerShellCommand(@"$xml = [xml]::new(); $xml.Load('C:\Windows\Panther\unattend.xml'); $sb = [scriptblock]::Create( $xml.unattend.Extensions.ExtractScript ); Invoke-Command -ScriptBlock $sb -ArgumentList $xml;")
);
}
XmlElement file = Document.CreateElement("File", Constants.MyNamespaceUri);
file.SetAttribute("path", path);
extensions.AppendChild(file);
if (useCDataSection)
{
file.AppendChild(Document.CreateCDataSection(Util.Indent(content)));
}
else
{
file.AppendChild(Document.CreateTextNode(Util.Indent(content)));
}
}
}
}