use appropriate elevation verb bases on OS

This commit is contained in:
Marcello 2024-10-25 00:15:35 +02:00
parent 28e67d7d28
commit e1e6a384c0
Signed by: m-lamonaca
SSH key fingerprint: SHA256:8db8uii6Gweq7TbKixFBioW2T8CbgtyFETyYL3cr3zk

View file

@ -26,36 +26,49 @@ internal static class ScriptExecutor
).ConfigureAwait(ConfigureAwaitOptions.None); ).ConfigureAwait(ConfigureAwaitOptions.None);
} }
private static ProcessStartInfo? GetExecutableProcessInfo(FileInfo file, bool elevated) => private static string GetElevationVerb(bool elevated)
file.Extension switch
{ {
".bat" if (!elevated)
or ".cmd" {
=> new ProcessStartInfo return string.Empty;
}
var platform = Environment.OSVersion.Platform;
return platform switch
{
PlatformID.Win32NT => "runas /user:Administrator",
PlatformID.Unix or PlatformID.MacOSX => "sudo",
_ => string.Empty,
};
}
private static ProcessStartInfo? GetExecutableProcessInfo(FileInfo file, bool elevated)
{
var verb = GetElevationVerb(elevated);
return file.Extension switch
{
".bat" or ".cmd" => new ProcessStartInfo
{ {
FileName = "cmd", FileName = "cmd",
Arguments = $"/Q /C .\\{file.Name}", Arguments = $"/Q /C {file.Name}",
Verb = elevated ? "runas /user:Administrator" : string.Empty, Verb = verb,
WorkingDirectory = file.DirectoryName WorkingDirectory = file.DirectoryName,
}, },
".ps1" ".ps1" => new ProcessStartInfo
=> new ProcessStartInfo
{ {
FileName = "powershell.exe", FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy Bypass -File .\\{file.Name}", Arguments = $"-NoProfile -ExecutionPolicy Bypass -File {file.Name}",
Verb = elevated ? "runas /user:Administrator" : string.Empty, Verb = verb,
WorkingDirectory = file.DirectoryName WorkingDirectory = file.DirectoryName,
}, },
".sh" ".sh" or ".zsh" or ".fish" => new ProcessStartInfo
or ".zsh"
or ".fish"
=> new ProcessStartInfo
{ {
FileName = "sh", FileName = "sh",
Arguments = $"-c ./{file.Name}", Arguments = $"-c {file.Name}",
Verb = elevated ? "sudo" : string.Empty, Verb = verb,
WorkingDirectory = file.DirectoryName WorkingDirectory = file.DirectoryName,
}, },
_ => null _ => null,
}; };
}
} }