Home

Awesome

gsudo - a sudo for Windows

Join the chat at https://gitter.im/gsudo/community CI Build Chocolatey Downloads GitHub Downloads

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

gsudo demo

(with gsudo config CacheMode auto)


Features

Installation

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:

<details> <summary>2. Invoke-gsudo wrapper function: (much slower)</summary>
# 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)
</details> <details> <summary>3. Manual string interpolation. (not recommended) </summary> 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"
</details>

PowerShell Module


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:

In any case, you can stop all cache sessions with gsudo -k.

Learn more

Known issues

FAQ

Please support gsudo! 💵