2
0

UWPHelper.cs 2.7 KB

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