UWPHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections.Generic;
  2. using System.Collections.ObjectModel;
  3. using System.Management.Automation;
  4. namespace Optimizer {
  5. internal static class UWPHelper {
  6. internal static List<KeyValuePair<string, string>> GetUWPApps(bool showAll) {
  7. List<KeyValuePair<string, string>> modernApps = new List<KeyValuePair<string, string>>();
  8. if (Utilities.CurrentWindowsVersion == WindowsVersion.Windows8) {
  9. showAll = true;
  10. }
  11. using (PowerShell script = PowerShell.Create()) {
  12. if (showAll) {
  13. script.AddScript("Get-AppxPackage | Select Name,InstallLocation");
  14. }
  15. else {
  16. script.AddScript(@"Get-AppxPackage | Where {$_.NonRemovable -like ""False""} | Select Name,InstallLocation");
  17. }
  18. string[] tmp;
  19. Collection<PSObject> psResult;
  20. try {
  21. psResult = script.Invoke();
  22. }
  23. catch {
  24. return modernApps;
  25. }
  26. if (psResult == null) return modernApps;
  27. foreach (PSObject x in psResult) {
  28. tmp = x.ToString().Replace("@", string.Empty).Replace("{", string.Empty).Replace("}", string.Empty).Replace("Name=", string.Empty).Replace("InstallLocation=", string.Empty).Trim().Split(';');
  29. if (!modernApps.Exists(i => i.Key == tmp[0])) {
  30. modernApps.Add(new KeyValuePair<string, string>(tmp[0], tmp[1]));
  31. }
  32. }
  33. }
  34. return modernApps;
  35. }
  36. internal static bool UninstallUWPApp(string appName) {
  37. using (PowerShell script = PowerShell.Create()) {
  38. script.AddScript(string.Format("Get-AppxPackage -AllUsers '{0}' | Remove-AppxPackage", appName));
  39. script.Invoke();
  40. return script.Streams.Error.Count > 0;
  41. // not working on Windows 7 anymore
  42. //return script.HadErrors;
  43. }
  44. }
  45. internal static bool RestoreAllUWPApps() {
  46. string cmd = "Get-AppxPackage -AllUsers | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register \"$($_.InstallLocation)\\AppXManifest.xml\"}";
  47. using (PowerShell script = PowerShell.Create()) {
  48. script.AddScript(cmd);
  49. script.Invoke();
  50. return script.Streams.Error.Count > 0;
  51. }
  52. }
  53. }
  54. }