Top Related Projects
PowerShell for every system!
A command-line installer for Windows.
Lovely console emulator package for Windows
The new Windows Terminal and the original Windows console host, all in the same place!
A fork of Git containing Windows-specific patches.
Chocolatey - the package manager for Windows
Quick Overview
gsudo is a sudo equivalent for Windows, allowing users to run commands with elevated privileges. It provides a seamless way to execute programs or commands as an administrator without leaving the current console window, enhancing productivity and security for Windows power users and developers.
Pros
- Seamless elevation of privileges without opening a new console window
- Supports both command-line and GUI applications
- Offers a cache feature to reduce repeated UAC prompts
- Highly configurable with various options and settings
Cons
- Limited to Windows operating systems
- May require additional setup and configuration for optimal use
- Potential security risks if not used carefully
- Learning curve for users unfamiliar with sudo-like tools on Windows
Getting Started
-
Install gsudo using winget:
winget install gerardog.gsudo
-
Or install using Chocolatey:
choco install gsudo
-
Basic usage:
gsudo command_to_run
-
To elevate the current console:
gsudo
-
To run a command as a different user:
gsudo -u username command_to_run
For more advanced usage and configuration options, refer to the official documentation on the GitHub repository.
Competitor Comparisons
PowerShell for every system!
Pros of PowerShell
- Comprehensive scripting and automation platform with extensive built-in cmdlets
- Cross-platform support (Windows, macOS, Linux)
- Deep integration with Windows systems and .NET framework
Cons of PowerShell
- Larger footprint and resource usage
- Steeper learning curve for users unfamiliar with PowerShell syntax
- Slower startup time compared to lightweight alternatives
Code Comparison
PowerShell:
$process = Start-Process notepad -Verb RunAs -PassThru
$process.WaitForExit()
gsudo:
gsudo notepad
Key Differences
- gsudo focuses on elevating privileges for command execution, while PowerShell is a full-featured scripting environment
- gsudo provides a simpler syntax for privilege elevation, making it more accessible for quick tasks
- PowerShell offers more advanced scripting capabilities and system management features
- gsudo is lightweight and faster for simple elevation tasks, while PowerShell provides a more comprehensive toolset
Use Cases
- Use gsudo for quick, one-off privilege elevations or simple scripts requiring admin rights
- Choose PowerShell for complex automation, system administration tasks, and cross-platform scripting needs
Community and Support
- PowerShell has a larger community, extensive documentation, and official Microsoft support
- gsudo is a smaller project but actively maintained and focused on its specific use case
A command-line installer for Windows.
Pros of Scoop
- Package manager for Windows, offering a wide range of software installations
- Allows easy installation and management of multiple versions of software
- Provides a consistent command-line interface for software management
Cons of Scoop
- Limited to package management and software installation
- May require more setup and configuration for specific use cases
- Not focused on privilege elevation or system administration tasks
Code Comparison
Scoop (installing a package):
scoop install git
gsudo (running a command with elevated privileges):
gsudo powershell -Command "Get-Service"
Key Differences
- Purpose: Scoop is a package manager, while gsudo is a sudo-like tool for Windows
- Functionality: Scoop focuses on software installation and management, gsudo on privilege elevation
- Use cases: Scoop is ideal for developers and power users managing software, gsudo for system administrators and users needing occasional elevated privileges
Conclusion
Scoop and gsudo serve different purposes in the Windows ecosystem. Scoop excels at package management and software installation, providing a streamlined way to manage multiple software versions. gsudo, on the other hand, focuses on providing a sudo-like experience for Windows, allowing users to easily elevate privileges for specific commands or processes. Both tools can be valuable in a Windows environment, depending on the user's needs and workflow.
Lovely console emulator package for Windows
Pros of Cmder
- Provides a full-featured console emulator with a rich set of features
- Includes built-in support for multiple shells (CMD, PowerShell, Git Bash)
- Offers a customizable user interface with themes and color schemes
Cons of Cmder
- Larger installation footprint compared to gsudo
- May have a steeper learning curve for users new to console emulators
- Not specifically designed for privilege elevation tasks
Code Comparison
Cmder (ConEmu configuration):
<key name="Tasks" modified="2023-04-01 12:00:00" build="180626">
<value name="{Shells::cmd}" modified="2023-04-01 12:00:00" type="string" data="%windir%\system32\cmd.exe /k "%ConEmuBaseDir%\CmdInit.cmd""/>
<value name="{Shells::PowerShell}" modified="2023-04-01 12:00:00" type="string" data="powershell.exe"/>
</key>
gsudo (usage example):
gsudo powershell -Command "Get-Process"
While Cmder provides a comprehensive console environment, gsudo focuses specifically on privilege elevation for command execution. Cmder offers a more feature-rich experience for general console use, while gsudo excels in simplifying administrative task execution across different shells.
The new Windows Terminal and the original Windows console host, all in the same place!
Pros of Terminal
- Comprehensive terminal emulator with extensive features and customization options
- Official Microsoft product with robust support and regular updates
- Supports multiple shells, tabs, and panes for enhanced productivity
Cons of Terminal
- Larger application footprint and resource usage
- Steeper learning curve for advanced features and customization
- Not specifically designed for privilege elevation scenarios
Code Comparison
Terminal (settings.json):
{
"defaultProfile": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"profiles": {
"list": [
{
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"name": "Windows PowerShell",
"commandline": "powershell.exe"
}
]
}
}
gsudo (usage example):
gsudo powershell -Command "Get-Process"
Summary
Terminal is a feature-rich terminal emulator with extensive customization options, while gsudo is a lightweight tool specifically designed for privilege elevation in Windows. Terminal offers a more comprehensive environment for various command-line tasks, whereas gsudo focuses on providing a simple and efficient way to run commands with elevated privileges. The choice between the two depends on the specific use case and requirements of the user.
A fork of Git containing Windows-specific patches.
Pros of Git for Windows
- Comprehensive Git implementation for Windows, including GUI and command-line tools
- Integrates well with Windows Explorer and provides a Unix-like command-line experience
- Regularly updated with new Git features and security patches
Cons of Git for Windows
- Larger installation footprint compared to gsudo
- Primarily focused on Git functionality, not a general-purpose elevation tool
- May include unnecessary components for users who only need basic Git functionality
Code Comparison
Git for Windows (bash.exe):
#!/usr/bin/env sh
# Copyright (C) 2009, 2010 Avery Pennarun <apenwarr@gmail.com>
if test -n "$MSYSTEM" && test -z "$TERM"; then
TERM=cygwin
fi
gsudo (Program.cs):
public static int Main(string[] args)
{
try
{
return new CommandExecutor().Execute(args);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return -1;
}
}
While Git for Windows focuses on providing a complete Git ecosystem for Windows users, gsudo is a lightweight tool specifically designed for elevating privileges in Windows command-line environments. Git for Windows offers a more comprehensive solution for Git-related tasks, while gsudo provides a simpler and more focused approach to privilege elevation.
Chocolatey - the package manager for Windows
Pros of Choco
- Comprehensive package management system for Windows
- Large community-maintained package repository
- Supports automation and scripting for software deployment
Cons of Choco
- Requires administrative privileges for most operations
- Can be complex to set up and configure for beginners
- May introduce potential security risks if untrusted packages are installed
Code Comparison
Choco
choco install nodejs
choco upgrade all
choco uninstall firefox
gsudo
gsudo choco install nodejs
gsudo powershell -Command "Get-Process"
gsudo cmd /c "echo Hello from elevated CMD"
Key Differences
- Choco is a package manager, while gsudo is a sudo-like tool for Windows
- gsudo focuses on elevating privileges for specific commands, whereas Choco manages software installations
- Choco requires administrative rights for most operations, while gsudo allows running elevated commands from non-admin prompts
Use Cases
- Use Choco for managing software installations and updates across Windows systems
- Use gsudo for running specific commands or scripts with elevated privileges without opening a new admin prompt
Both tools can complement each other, with gsudo potentially being used to elevate Choco commands when needed.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
gsudo - a sudo for Windows
gsudo is a sudo
equivalent for Windows, with a similar user-experience as the original Unix/Linux sudo.
Allows you to run a command (or re-launch your current shell) with elevated permissions, in the current console window or a new one.
Just prepend gsudo
(or the sudo
alias) to your command and it will run elevated. For PowerShell use this syntax: gsudo { ScriptBlock }
One UAC popup will appear each time. You can see less popups if you enable gsudo cache.
It detects your current shell and elevates your command as native shell commands. (Supports Cmd
, PowerShell
, WSL
, git-bash
, MinGW
, Cygwin
, Yori
, Take Command
, BusyBox
& NuShell
.)
Table of contents
â Extended documentation available at: https://gerardog.github.io/gsudo/
Demo
(with gsudo config CacheMode auto
)
Features
-
Elevated commands are shown in the current console. No new window (unless you specify
-n
) -
Credentials cache:
gsudo
can elevate many times showing only one UAC pop-up if the user opts-in to enable the cache. -
Detects your current shell (Supports
CMD
,PowerShell
,WSL
,Bash for Windows
(Git-Bash/MinGW/MSYS2/Cygwin),Yori
,Take Command
andNuShell
), and elevates your command correctly. -
Supports being used on scripts:
- Outputs StdOut/StdErr can be piped or captured (e.g.
gsudo dir | findstr /c:"bytes free" > FreeSpace.txt
) and exit codes too (%errorlevel%
). Ifgsudo
fails to elevate, the exit code will be 999. - If
gsudo
is invoked from an already elevated console, it will just run the command (it won't fail). So, you don't have to worry if you rungsudo
or a script that usesgsudo
from an already elevated console. (The UAC popup will not appear, as no elevation is required)
- Outputs StdOut/StdErr can be piped or captured (e.g.
-
gsudo !!
elevates the last executed command. Works on CMD, Git-Bash, MinGW, Cygwin (and PowerShell with gsudo module only)
Installation
- Using Scoop:
scoop install gsudo
- Using WinGet:
winget install gerardog.gsudo
- Using Chocolatey:
choco install gsudo
- Manual Setup: download and run the proper
MSI
installer for you system from the latest release. - Running this line: (script):
PowerShell -Command "Set-ExecutionPolicy RemoteSigned -scope Process; [Net.ServicePointManager]::SecurityProtocol = 'Tls12'; iwr -useb https://raw.githubusercontent.com/gerardog/gsudo/master/installgsudo.ps1 | iex"
- Portable:
- Download
gsudo.portable.zip
from the latest release. - Extract the folder corresponding to your processor architecture (x64, x86, or arm64) from the zip file to a suitable directory on your computer.
- Optionally, add that directory to your system's PATH environment variable if it's not already accessible.
- Download
Please restart all your console windows after installing to ensure that the PATH
environment variable is refreshed.
Note: gsudo.exe
is portable. No windows service is required or system change is done, except adding it to the Path.
Usage
gsudo [options] # Starts your current shell elevated
gsudo [options] {command} [args] # Runs {command} with elevated permissions
gsudo cache [on | off | help] # Starts/Stops a credentials cache session. (less UAC popups)
gsudo status [--json | filter ] # Shows current user, cache and console status.
gsudo !! # Re-run last command as admin. (YMMV)
New Window options:
-n | --new # Starts the command in a new console/window (and returns immediately).
-w | --wait # When in new console, wait for the command to end.
--keepShell # After running a command, keep the elevated shell open.
--keepWindow # After running a command in a new console, ask for keypress before closing the console/window.
Security options:
-u | --user {usr} # Run as the specified user. Asks for password. For local admins shows UAC unless '-i Medium'
-i | --integrity {v} # Specify integrity level: Untrusted, Low, Medium, MediumPlus, High (default), System
-s | --system # Run as Local System account (NT AUTHORITY\SYSTEM).
--ti # Run as member of NT SERVICE\TrustedInstaller
-k # Kills all cached credentials. The next time gsudo is run a UAC popup will be appear.
Shell related options:
-d | --direct # Skips Shell detection. Assume CMD shell or CMD {command}.
--loadProfile # When elevating PowerShell commands, load user profile.
Other options:
--loglevel {val} # Set minimum log level to display: All, Debug, Info, Warning, Error, None
--debug # Enable debug mode.
--copyns # Connect network drives to the elevated user. Warning: Verbose, interactive asks for credentials
--copyev # (deprecated) Copy environment variables to the elevated process. (not needed on default console mode)
--chdir {dir} # Change the current directory to {dir} before running the command.
Note: You can use anywhere the sudo
alias created by the installers.
Examples:
gsudo # elevates the current shell in the current console window (Supports Cmd/PowerShell/Pwsh Core/Yori/Take Command/git-bash/cygwin)
gsudo -n # launch the current shell elevated in a new console window
gsudo -n -w powershell ./Do-Something.ps1 # launch in new window and wait for exit
gsudo notepad %windir%\system32\drivers\etc\hosts # launch windows app
sudo notepad # sudo alias built-in
# redirect/pipe input/output/error example
gsudo dir | findstr /c:"bytes free" > FreeSpace.txt
gsudo config LogLevel "Error" # Configure Reduced logging
gsudo config Prompt "$P [elevated]$G " # Configure a custom Elevated Prompt
gsudo config Prompt --reset # Reset to default value
# Enable credentials cache (less UAC popups):
gsudo config CacheMode Auto
Usage from PowerShell / PowerShell Core
gsudo
detects if invoked from PowerShell and elevates PS commands (unless -d
is used to elevate CMD commands).
The command to elevate will run in a different process, so it can't access the parent $variables
and scope.
To elevate a commands or script block: Wrap it in {curly braces}.
# Syntax:
gsudo { ScriptBlock }
gsudo [options] { ScriptBlock } [-args $argument1[..., $argumentN]] ;
# Examples:
gsudo { Write-Output "Hello World" }
# Pass arguments with -args
$MyString = "Hello World"
gsudo { Write-Output $args[0] } -args $MyString
# Output is serialized as PSObjects with properties.
$services = gsudo { Get-Service 'WSearch', 'Winmgmt'}
Write-Output $services.DisplayName
# Inputs too: Example elevated iteration of a list.
Get-ChildItem . | gsudo { $Input.CreationTime}
Alternative syntaxes:
2. Invoke-gsudo wrapper function: (much slower)
# Pass values (not variables by reference) by prefixing `$using:`. I.E.
$MyString = "Hello World"
Invoke-Gsudo { Write-Output $using:MyString }
# Syntax:
Invoke-Gsudo [-ScriptBlock] <ScriptBlock>
[[-ArgumentList] <Object[]>]
[-InputObject <PSObject>]
[-LoadProfile | -NoProfile]
[-Credential <PSCredential>]
- PowerShell function.
- Performs auto serialization of inputs & outputs.
- You can prefix variables with the `$using:` scope modifier (like `$using:variableName`) and their serialized value is applied.
- Use `-LoadProfile` or `-NoProfile` to override profile loading or not.
- Use `-Credential` option for Run As User (same as `-u` but for `Get-Credentials`).
- Better forwarding of your current context to the elevated instance (current Location, $ErrorActionPreference)
3. Manual string interpolation. (not recommended)
I don't recommend this approach as it is really hard to do proper escape all special characters.Usage: gsudo 'string literal'
# Variable substitutions example:
$file='C:\My Secret.txt';
$algorithm='md5';
$hash = gsudo "(Get-FileHash '$file' -Algorithm $algorithm).Hash"
# or
$hash = gsudo "(Get-FileHash ""$file"" -Algorithm $algorithm).Hash"
- Accepts a string literal with the command to elevate.
- Returns a list of strings.
PowerShell Module
-
Optional: Import module
gsudoModule.psd1
into your PowerShell Profile:- Adds syntax auto-complete to gsudo in PowerShell. Plus, it suggests the 3 previous commands, making your workflow smoother than ever!
- Enables
gsudo !!
on Powershell, to elevate the last executed command. - Adds Functions:
Test-IsGsudoCacheAvailable
Returns true if a gsudo cache is active (meaning elevation with no UAC is possible).Test-IsProcessElevated
: Returns true if the current process is elevated.Test-IsAdminMember
: Returns true if the current user is member of theLocal Administrators
groups, which means it can elevate with.
# Add the following line to your $PROFILE Import-Module "gsudoModule" # Or run: Write-Output "`nImport-Module `"gsudoModule`"" | Add-Content $PROFILE
- If you haven't already customized your PowerShell prompt (for example by installing Oh-My-Posh), you can easily add a red
#
indicating that the current process is elevated:
To do so add this line to your profile (after importing
gsudoModule
):Set-Alias Prompt gsudoPrompt
Usage from WSL (Windows Subsystem for Linux)
On WSL, elevation and root
are different concepts. root
allows full administration of WSL but not the windows system. Use WSL's native su
or sudo
to gain root
access. To get admin privilege on the Windows box you need to elevate the WSL.EXE process. gsudo
allows that (a UAC popup will appear).
On WSL bash, prepend gsudo
to elevate WSL commands or gsudo -d
for CMD commands.
# elevate default shell
PC:~$ gsudo
# run elevated WSL command
PC:~$ gsudo mkdir /mnt/c/Windows/MyFolder
# run elevated Windows command
PC:~$ gsudo -d notepad C:/Windows/System32/drivers/etc/hosts
PC:~$ gsudo -d "notepad C:\Windows\System32\drivers\etc\hosts"
# test for gsudo and command success
retval=$?;
if [ $retval -eq 0 ]; then
echo "Success";
elif [ $retval -eq $((999 % 256)) ]; then # gsudo failure exit code (999) is read as 231 on wsl (999 mod 256)
echo "gsudo failed to elevate!";
else
echo "Command failed with exit code $retval";
fi;
Configuration
gsudo config # Show current config settings & values.
gsudo config {key} [--global] [value] # Read or write a user setting
gsudo config {key} [--global] --reset # Reset config to default value
--global # Affects all users (overrides user settings)
Credentials Cache
The Credentials Cache
, if enabled and active, allows to elevate several times from a parent process with only one UAC pop-up. After 5 minutes without elevations, the cache session closes automatically (Configurable timeout via gsudo config CacheDuration
).
While this very convenient, it's important to understand its potential security risks. Even if gsudo itself is secure, the inherent vulnerability lies in the host process. If your system is already compromised by a malicious process, it can manipulate the permitted process (e.g., Cmd/Powershell) and force an active gsudo cache instance to elevate privileges without triggering a UAC prompt.
This risk is the trade-off for using the Credentials Cache. The cache is safe to use as long as you are confident there are no malicious processes running on your system.
Here are the Credentials Cache
Modes:
Explicit:
(default) Every elevation shows a UAC popup, unless a cache session is started manually...- To start or stop a cache session run:
gsudo cache {on | off}
- This is the default mode. (Use
gsudo config CacheMode Explicit
to revert to this value).
- To start or stop a cache session run:
Auto:
Similar to unix-sudo. The first elevation shows a UAC popup and starts a cache session automatically.- Run
gsudo config CacheMode Auto
to use this mode.
- Run
Disabled:
Every elevation shows a UAC popup, and trying to start a cache session will throw an error..- Run
gsudo config CacheMode Disabled
to use this mode.
- Run
In any case, you can stop all cache sessions with gsudo -k
.
Known issues
-
The elevated instances do not have access to the network shares connected on the non-elevated space. This is not a
gsudo
issue but how Windows works. Use--copyNS
to replicate Network Shares into the elevated session, but this is not bi-directional and is interactive (may prompt for user/password). -
gsudo.exe
can be placed on a network share and invoked as\\server\share\gsudo {command}
but doesn't work if your current folder is a network drive. For example do not map\\server\share\
toZ:
and thenZ:\>gsudo do-something
. -
Please report issues in the Issues section.
FAQ
-
Why is it named
gsudo
instead of justsudo
?When I created
gsudo
, there were othersudo
packages on most Windows popular package managers such asChocolatey
andScoop
, so I had no other choice to pick another name.gsudo
installers create an alias forsudo
, so feel free to usesudo
on your command line to invokegsudo
. -
Which dotnet version is built with?
Versions prior to v1.3.0 used .NET 4.6 because it was included in every Windows 10/11 installation.
From v1.4.0 up to v2.5.1, gsudo has been built using .net7.0 NativeAOT. This approach offers faster load times, reduced memory usage, and allows the tool to run on machines without any .NET runtime installed.
Starting with v2.6.0, we've migrated to net9.0 due to the end-of-life of net7.0.
-
Is
gsudo
a port of*nix sudo
?No.
gsudo
reminds of the original sudo regarding user expectations. Manysudo
features are*nix
specific and could never have aWindows
counterpart. Other features (such assudoers
) could potentially be implemented but are not at this point. -
What are the requirements? Does it work in Windows 7/8?
It works on Win7 SP1 onwards. Some features may only work in Windows 10/11, like elevating as TrustedInstaller.
-
How do I return to the previous security level after using gsudo?
In the same way as you would with
Unix/Linux sudo
:gsudo
does not alter the current process, instead it launches a new process with different permissions/integrity level. To go back to the previous level, just end the new process. ForCommand Prompt
orPowerShell
just typeexit
.
Please support gsudo! ðµ
- Please give us a star! â
- Help spread the word by mentioning
gsudo
in social networks! - Sponsor or Donate
Top Related Projects
PowerShell for every system!
A command-line installer for Windows.
Lovely console emulator package for Windows
The new Windows Terminal and the original Windows console host, all in the same place!
A fork of Git containing Windows-specific patches.
Chocolatey - the package manager for Windows
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot