Skip to content

Portable Tool for an Ideal Windows Setup

fix exe path validation and safer Process.Start #79 & fix handle null InstalledPackagesCache when registry returns null #75

Greedeksd92408758839
diff --git a/.Source/GTweak/Utilities/Controls/PathLocator.cs b/.Source/GTweak/Utilities/Controls/PathLocator.cs
index 273b585c..3827596d 100644
--- a/.Source/GTweak/Utilities/Controls/PathLocator.cs
+++ b/.Source/GTweak/Utilities/Controls/PathLocator.cs
@@ -1,6 +1,7 @@
using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
using System.IO;
-using System.Linq;
namespace GTweak.Utilities.Controls
{
@@ -25,16 +26,220 @@ namespace GTweak.Utilities.Controls
internal static class Executable
{
- private static string FindExecutablePath(string name)
+ private static readonly ConcurrentDictionary<string, string> exeCache = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+
+ internal static string FindExecutablePath(params string[] names)
{
- string[] searchDir = Environment.GetEnvironmentVariable("PATH")?.Split(Path.PathSeparator) ?? Array.Empty<string>();
- searchDir = searchDir.Concat(new[] { Environment.SystemDirectory, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32"),
- Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "SysWOW64")})
- .Concat(Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)) ? Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "PowerShell*", SearchOption.TopDirectoryOnly) : Array.Empty<string>())
- .Concat(Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)) ? Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "PowerShell*", SearchOption.TopDirectoryOnly) : Array.Empty<string>()
- ).Where(dir => !string.IsNullOrEmpty(dir)).ToArray();
-
- return searchDir.Select(dir => Path.Combine(dir, name)).FirstOrDefault(File.Exists);
+ if (names == null || names.Length == 0)
+ {
+ return string.Empty;
+ }
+
+ for (int ni = 0; ni < names.Length; ni++)
+ {
+ string name = names[ni];
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ continue;
+ }
+
+ if (exeCache.TryGetValue(name, out string cachedValue))
+ {
+ if (!string.IsNullOrEmpty(cachedValue))
+ {
+ return cachedValue;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ if (Path.IsPathRooted(name))
+ {
+ string absolute = File.Exists(name) ? name : string.Empty;
+ exeCache.TryAdd(name, absolute);
+ if (!string.IsNullOrEmpty(absolute))
+ {
+ return absolute;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ string pathextRaw = Environment.GetEnvironmentVariable("PATHEXT");
+ if (string.IsNullOrEmpty(pathextRaw))
+ {
+ pathextRaw = ".EXE";
+ }
+
+ string[] pathextEntries = pathextRaw.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
+ for (int pei = 0; pei < pathextEntries.Length; pei++)
+ {
+ string e = pathextEntries[pei].Trim().Trim('"');
+ if (string.IsNullOrEmpty(e))
+ {
+ e = ".EXE";
+ }
+
+ if (e[0] != '.')
+ {
+ e = "." + e;
+ }
+
+ pathextEntries[pei] = e;
+ }
+
+ string[] namesToTry;
+ if (Path.HasExtension(name))
+ {
+ namesToTry = new[] { name };
+ }
+ else
+ {
+ List<string> tmp = new List<string>(pathextEntries.Length);
+ for (int pei = 0; pei < pathextEntries.Length; pei++)
+ {
+ tmp.Add(name + pathextEntries[pei]);
+ }
+
+ namesToTry = tmp.ToArray();
+ }
+
+ if (name.IndexOf(Path.DirectorySeparatorChar) >= 0 || name.IndexOf(Path.AltDirectorySeparatorChar) >= 0)
+ {
+ string current = Directory.GetCurrentDirectory();
+ for (int ti = 0; ti < namesToTry.Length; ti++)
+ {
+ string candidateRel = Path.Combine(current, namesToTry[ti]);
+ try
+ {
+ if (File.Exists(candidateRel))
+ {
+ exeCache.TryAdd(name, candidateRel);
+ return candidateRel;
+ }
+ }
+ catch (Exception ex)
+ {
+ ErrorLogging.LogDebug(ex);
+ }
+ }
+ }
+
+ HashSet<string> searchDirs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+
+ string pathEnv = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
+ string[] pathEntries = pathEnv.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
+ for (int pe = 0; pe < pathEntries.Length; pe++)
+ {
+ string entry = pathEntries[pe].Trim().Trim('"');
+ if (!string.IsNullOrEmpty(entry))
+ {
+ searchDirs.Add(entry);
+ }
+ }
+
+ string systemDir = Environment.SystemDirectory;
+ if (!string.IsNullOrEmpty(systemDir))
+ {
+ searchDirs.Add(systemDir);
+ }
+
+ string windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
+ if (!string.IsNullOrEmpty(windows))
+ {
+ searchDirs.Add(Path.Combine(windows, "System32"));
+ searchDirs.Add(Path.Combine(windows, "Sysnative"));
+ searchDirs.Add(Path.Combine(windows, "SysWOW64"));
+ }
+
+ bool found = false;
+ string foundPath = string.Empty;
+ foreach (string dir in searchDirs)
+ {
+ try
+ {
+ if (!Directory.Exists(dir))
+ {
+ continue;
+ }
+
+ for (int ti = 0; ti < namesToTry.Length; ti++)
+ {
+ string candidate = Path.Combine(dir, namesToTry[ti]);
+ try
+ {
+ if (File.Exists(candidate))
+ {
+ found = true;
+ foundPath = candidate;
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ ErrorLogging.LogDebug(ex);
+ }
+ }
+
+ if (found)
+ {
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ ErrorLogging.LogDebug(ex);
+ }
+ }
+
+ if (found)
+ {
+ exeCache.TryAdd(name, foundPath);
+ return foundPath;
+ }
+
+ string[] programRoots = new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) };
+
+ for (int r = 0; r < programRoots.Length; r++)
+ {
+ string root = programRoots[r];
+ if (string.IsNullOrEmpty(root) || !Directory.Exists(root))
+ {
+ continue;
+ }
+
+ try
+ {
+ string[] candidateDirs = Directory.GetDirectories(root, "PowerShell*", SearchOption.TopDirectoryOnly);
+ for (int d = 0; d < candidateDirs.Length; d++)
+ {
+ string candidateDir = candidateDirs[d];
+ for (int ti = 0; ti < namesToTry.Length; ti++)
+ {
+ string candidate = Path.Combine(candidateDir, namesToTry[ti]);
+ try
+ {
+ if (File.Exists(candidate))
+ {
+ exeCache.TryAdd(name, candidate);
+ return candidate;
+ }
+ }
+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }
+ }
+ }
+ }
+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }
+ }
+
+ exeCache.TryAdd(name, string.Empty);
+ }
+
+ return string.Empty;
}
internal static (string Normal, string Block) FindWindowsUpdateExe(string normalName, string blockName)
@@ -76,7 +281,7 @@ namespace GTweak.Utilities.Controls
internal static readonly string CommandShell = FindExecutablePath("cmd.exe");
- internal static readonly string PowerShell = FindExecutablePath("pwsh.exe") ?? FindExecutablePath("powershell.exe");
+ internal static readonly string PowerShell = FindExecutablePath("pwsh.exe", "powershell.exe");
internal static readonly string BcdEdit = FindExecutablePath("bcdedit.exe");
diff --git a/.Source/GTweak/Utilities/Helpers/CommandExecutor.cs b/.Source/GTweak/Utilities/Helpers/CommandExecutor.cs
index 69f3a9c8..4033dc82 100644
--- a/.Source/GTweak/Utilities/Helpers/CommandExecutor.cs
+++ b/.Source/GTweak/Utilities/Helpers/CommandExecutor.cs
@@ -55,7 +55,7 @@ namespace GTweak.Utilities.Helpers
{
await Task.Run(() =>
{
- Process.Start(new ProcessStartInfo()
+ ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = isPowerShell ? PathLocator.Executable.PowerShell : PathLocator.Executable.CommandShell,
Arguments = isPowerShell ? $"-NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command \"{command}\"" : command,
@@ -63,8 +63,18 @@ namespace GTweak.Utilities.Helpers
UseShellExecute = true,
Verb = "runas",
CreateNoWindow = true
- });
- });
+ };
+
+ using Process process = new Process { StartInfo = startInfo };
+ try
+ {
+ process.Start();
+ }
+ catch (Exception ex)
+ {
+ ErrorLogging.LogDebug(ex);
+ }
+ }).ConfigureAwait(false);
}
internal static async Task InvokeRunCommand(string command, bool isPowerShell = false)
@@ -80,9 +90,16 @@ namespace GTweak.Utilities.Helpers
CreateNoWindow = true
};
- using var process = new Process { StartInfo = startInfo };
- process.Start();
- await process.WaitForExitAsync().ConfigureAwait(false);
+ using Process process = new Process { StartInfo = startInfo };
+ try
+ {
+ process.Start();
+ await process.WaitForExitAsync().ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ ErrorLogging.LogDebug(ex);
+ }
}
internal static Task WaitForExitAsync(this Process process)
diff --git a/.Source/GTweak/Utilities/Tweaks/UninstallingPakages.cs b/.Source/GTweak/Utilities/Tweaks/UninstallingPakages.cs
index 8be40f68..95742c1f 100644
--- a/.Source/GTweak/Utilities/Tweaks/UninstallingPakages.cs
+++ b/.Source/GTweak/Utilities/Tweaks/UninstallingPakages.cs
@@ -20,12 +20,32 @@ namespace GTweak.Utilities.Tweaks
internal static bool IsOneDriveInstalled => File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "OneDrive", "OneDrive.exe"));
private static bool _isLocalAccount = false;
+ internal static HashSet<string> InstalledPackagesCache = new HashSet<string>();
+
internal void GetInstalledPackages()
{
- InstalledPackagesCache = RegistryHelp.GetSubKeyNames<HashSet<string>>(Registry.CurrentUser, @"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages");
- OnPackagesChanged();
+ try
+ {
+ HashSet<string> keys = RegistryHelp.GetSubKeyNames<HashSet<string>>(Registry.CurrentUser, @"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages");
+ if (keys == null)
+ {
+ InstalledPackagesCache = new HashSet<string>();
+ }
+ else
+ {
+ InstalledPackagesCache = keys;
+ }
+ }
+ catch (Exception ex)
+ {
+ ErrorLogging.LogDebug(ex);
+ InstalledPackagesCache = new HashSet<string>();
+ }
+ finally
+ {
+ OnPackagesChanged();
+ }
}
- internal static HashSet<string> InstalledPackagesCache = new HashSet<string>();
internal static Dictionary<string, (string Alias, bool IsUnavailable, List<string> Scripts)> PackagesDetails = new Dictionary<string, (string Alias, bool IsUnavailable, List<string> Scripts)>()
{
@@ -139,7 +159,14 @@ namespace GTweak.Utilities.Tweaks
{
try
{
- var (Alias, _, Scripts) = PackagesDetails[packageName];
+ if (!PackagesDetails.TryGetValue(packageName, out var details))
+ {
+ ErrorLogging.LogDebug(new InvalidOperationException($"PackageDetails does not contain key '{packageName}'"));
+ return;
+ }
+
+ string Alias = details.Alias;
+ List<string> Scripts = details.Scripts;
List<string> packageNamesToRemove = new List<string> { packageName };
@@ -148,11 +175,12 @@ namespace GTweak.Utilities.Tweaks
packageNamesToRemove.Add(Alias);
}
- if (Scripts != null)
+ if (Scripts != null && Scripts.Count > 0)
{
packageNamesToRemove.AddRange(Scripts);
}
+
List<string> psCommands = packageNamesToRemove.SelectMany(name => new[]
{
$@"Get-AppxPackage -AllUsers | Where-Object {{ $_.Name -like '*{name}*' }} | ForEach-Object {{ Remove-AppxPackage -AllUsers -Package $_.PackageFullName }}",