Script for upgrading certain versions of AME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
12 KiB

1 year ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Security.AccessControl;
  8. using System.Security.Principal;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. using amecs;
  13. using Ameliorated.ConsoleUtils;
  14. using Microsoft.Win32;
  15. namespace ame_upgrade_preparation_tool
  16. {
  17. internal class Program
  18. {
  19. private static void RunAsUser(Action action)
  20. {
  21. var token = NSudo.GetUserToken();
  22. Task.Run((Action)Delegate.Combine((Action)(() => { NSudo.GetUserPrivilege(token); }),
  23. action)).Wait();
  24. Marshal.FreeHGlobal(token);
  25. }
  26. public static async Task Main(string[] args)
  27. {
  28. ConsoleTUI.Initialize("AME Upgrade Script");
  29. Console.WriteLine("\r\nChecking drives...");
  30. var drives = DriveInfo.GetDrives();
  31. List<string> driveLetters = new List<string>();
  32. foreach (var drive in drives)
  33. {
  34. try
  35. {
  36. if (Directory.GetFiles(drive.RootDirectory.FullName).Contains(Path.Combine(drive.RootDirectory.FullName, "setup.exe")) && Directory.GetDirectories(drive.RootDirectory.FullName).Contains(Path.Combine(drive.RootDirectory.FullName, "sources")))
  37. {
  38. try
  39. {
  40. string extension = Directory.GetFiles(Path.Combine(drive.RootDirectory.FullName, "sources")).Contains(Path.Combine(drive.RootDirectory.FullName, "sources", "install.wim")) ? ".wim" : Directory.GetFiles(Path.Combine(drive.RootDirectory.FullName, "sources")).Contains(Path.Combine(drive.RootDirectory.FullName, "sources", "install.esd")) ? ".esd" : null;
  41. if (string.IsNullOrEmpty(extension))
  42. continue;
  43. /*
  44. var startInfo = new ProcessStartInfo
  45. {
  46. CreateNoWindow = true,
  47. UseShellExecute = false,
  48. WindowStyle = ProcessWindowStyle.Normal,
  49. RedirectStandardError = true,
  50. RedirectStandardOutput = true,
  51. FileName = "DISM",
  52. Arguments = "/Get-WimInfo /WimFile:\"" + Path.Combine(drive.RootDirectory.FullName, "sources", "install" + extension) + '"'
  53. };
  54. var exeProcess = new Process
  55. {
  56. StartInfo = startInfo,
  57. EnableRaisingEvents = true
  58. };
  59. string versionString = null;
  60. bool Win11 = false;
  61. exeProcess.OutputDataReceived += delegate(object sender, DataReceivedEventArgs outLine)
  62. {
  63. if (!String.IsNullOrEmpty(outLine.Data))
  64. {
  65. var outputString = outLine.Data;
  66. if (outputString.Contains("Version: "))
  67. {
  68. versionString = outputString.Substring(outputString.IndexOf(' ') + 1);
  69. }
  70. else if (outputString.Contains("Windows 11"))
  71. {
  72. Win11 = true;
  73. }
  74. }
  75. };
  76. exeProcess.Start();
  77. exeProcess.BeginOutputReadLine();
  78. bool exited = exeProcess.WaitForExit(5000);
  79. exeProcess.CancelOutputRead();
  80. if (versionString == null)
  81. {
  82. await Task.Delay(500);
  83. }
  84. */
  85. driveLetters.Add(drive.RootDirectory.FullName);
  86. } catch (Exception e)
  87. {
  88. driveLetters.Add(drive.RootDirectory.FullName);
  89. }
  90. }
  91. } catch
  92. {
  93. }
  94. }
  95. if (driveLetters.Count < 1)
  96. {
  97. Console.WriteLine("No mounted Windows ISO was detected.\r\n");
  98. new ChoicePrompt() { Text = "Press any key to Exit...", AnyKey = true}.Start();
  99. Environment.Exit(0);
  100. }
  101. if (driveLetters.Count > 1)
  102. {
  103. Console.WriteLine("Multiple ISOs detected, please dismount one.\r\n");
  104. new ChoicePrompt() { Text = "Press any key to Exit...", AnyKey = true}.Start();
  105. Environment.Exit(0);
  106. }
  107. var choice = new ChoicePrompt() { AllowEscape = false, Text = "\r\nThis will cause partial de-amelioration. Continue? (Y/N): " }.Start();
  108. if (choice.Value == 2)
  109. Environment.Exit(0);
  110. string Username = null;
  111. string UserDomain = null;
  112. string UserSID = null;
  113. try
  114. {
  115. NSudo.GetSystemPrivilege();
  116. RunAsUser(() =>
  117. {
  118. Username = WindowsIdentity.GetCurrent().Name.Split('\\').Last();
  119. UserDomain = WindowsIdentity.GetCurrent().Name.Split('\\').FirstOrDefault();
  120. UserSID = WindowsIdentity.GetCurrent().User.ToString();
  121. });
  122. } catch (Exception e)
  123. {
  124. }
  125. bool isSystem = WindowsIdentity.GetCurrent().IsSystem;
  126. try
  127. {
  128. string ID = null;
  129. var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
  130. foreach (var item in key.GetSubKeyNames())
  131. {
  132. try
  133. {
  134. if (((string)key.OpenSubKey(item).GetValue("DisplayName")).Equals("Open-Shell"))
  135. {
  136. ID = item;
  137. }
  138. } catch (Exception e)
  139. {
  140. }
  141. }
  142. if (ID != null)
  143. {
  144. Console.WriteLine("\r\nUninstalling Open-Shell...");
  145. var proc = Process.Start("MsiExec.exe", $"/X{ID} /quiet");
  146. proc.WaitForExit();
  147. if (UserSID != null)
  148. {
  149. try
  150. {
  151. var appData = (string)Registry.Users.OpenSubKey(UserSID + @"\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders").GetValue("AppData");
  152. if (Directory.Exists(Path.Combine(appData, "OpenShell")))
  153. Directory.Delete(Path.Combine(appData, "OpenShell"), true);
  154. } catch (Exception e)
  155. {
  156. Console.WriteLine("Error: " + e);
  157. }
  158. }
  159. await Task.Delay(5000);
  160. if (!Process.GetProcessesByName("explorer").Any())
  161. {
  162. if (isSystem)
  163. NSudo.RunProcessAsUser(NSudo.GetUserToken(), "explorer.exe", "");
  164. else
  165. Process.Start("explorer.exe");
  166. }
  167. }
  168. } catch (Exception e)
  169. {
  170. Console.WriteLine("Error: " + e.Message);
  171. }
  172. Console.WriteLine("\r\nReverting settings...");
  173. try
  174. {
  175. var polKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer", true);
  176. if (polKey.GetValueNames().Contains("SettingsPageVisibility", StringComparer.InvariantCultureIgnoreCase))
  177. {
  178. polKey.DeleteValue("SettingsPageVisibility");
  179. }
  180. if (UserSID != null)
  181. {
  182. new Reg.Value() { KeyName = @$"HKU\{UserSID}\SOFTWARE\Policies\Microsoft\Windows\Explorer", ValueName = "DisableNotificationCenter", Operation = Reg.RegistryValueOperation.Delete }.Apply();
  183. new Reg.Value() { KeyName = @$"HKU\{UserSID}\SOFTWARE\Classes\CLSID\{{27DD0F8B-3E0E-4ADC-A78A-66047E71ADC5}}\InprocServer32", ValueName = "", Type = Reg.RegistryValueType.REG_SZ, Data = ""}.Apply();
  184. }
  185. } catch (Exception e)
  186. {
  187. Console.WriteLine("Error: " + e.Message);
  188. }
  189. Thread.Sleep(3000);
  190. Console.WriteLine("\r\nApplying preparation settings...");
  191. try
  192. {
  193. new Reg.Key() { KeyName = @"HKLM\SYSTEM\Setup\LabConfig", Operation = RegistryOperation.Add }.Apply();
  194. new Reg.Value() { KeyName = @"HKLM\SYSTEM\Setup\LabConfig", ValueName = "BypassTPMCheck", Type = Reg.RegistryValueType.REG_DWORD, Data = 1 }.Apply();
  195. new Reg.Value() { KeyName = @"HKLM\SYSTEM\Setup\LabConfig", ValueName = "BypassCPUCheck", Type = Reg.RegistryValueType.REG_DWORD, Data = 1 }.Apply();
  196. new Reg.Value() { KeyName = @"HKLM\SYSTEM\Setup\LabConfig", ValueName = "BypassStorageCheck", Type = Reg.RegistryValueType.REG_DWORD, Data = 1 }.Apply();
  197. new Reg.Value() { KeyName = @"HKLM\SYSTEM\Setup\LabConfig", ValueName = "BypassSecureBootCheck", Type = Reg.RegistryValueType.REG_DWORD, Data = 1 }.Apply();
  198. new Reg.Value() { KeyName = @"HKLM\SYSTEM\Setup\LabConfig", ValueName = "BypassRAMCheck", Type = Reg.RegistryValueType.REG_DWORD, Data = 1 }.Apply();
  199. new Reg.Key() { KeyName = @"HKLM\SYSTEM\Setup\MoSetup", Operation = RegistryOperation.Add }.Apply();
  200. new Reg.Value() { KeyName = @"HKLM\SYSTEM\Setup\MoSetup", ValueName = "AllowUpgradesWithUnsupportedTPMOrCPU", Type = Reg.RegistryValueType.REG_DWORD, Data = 1 }.Apply();
  201. } catch (Exception e)
  202. {
  203. Console.WriteLine("Error: " + e.Message);
  204. }
  205. Thread.Sleep(1500);
  206. var fc = Console.ForegroundColor;
  207. Console.ForegroundColor = ConsoleColor.Green;
  208. Console.WriteLine("\r\nCompleted configuration");
  209. Console.ForegroundColor = fc;
  210. Console.WriteLine("\r\nStarting Windows Setup...");
  211. try
  212. {
  213. Process.Start(Path.Combine(driveLetters.First(), "setup.exe"), "/Auto Upgrade /DynamicUpdate Disable");
  214. } catch (Exception e)
  215. {
  216. fc = Console.ForegroundColor;
  217. Console.ForegroundColor = ConsoleColor.Red;
  218. Console.WriteLine("Error launching Windows Setup: " + e.Message);
  219. Console.ForegroundColor = fc;
  220. new ChoicePrompt() { Text = "Press any key to Exit...", AnyKey = true}.Start();
  221. Environment.Exit(0);
  222. }
  223. fc = Console.ForegroundColor;
  224. Console.ForegroundColor = ConsoleColor.Green;
  225. Console.WriteLine("\r\nSetup launch successful, exiting...");
  226. Thread.Sleep(6000);
  227. }
  228. }
  229. }