UWPHelper.cs 2.7 KB

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