Skip to content

Instantly share code, notes, and snippets.

@EDM115
Last active May 6, 2024 21:07
Show Gist options
  • Save EDM115/daff204ae4bb19f0a90291d036e433ed to your computer and use it in GitHub Desktop.
Save EDM115/daff204ae4bb19f0a90291d036e433ed to your computer and use it in GitHub Desktop.
sudo on PowerShell

sudo on PowerShell

Microsoft plans on adding a sudo like command on windows (info and controversy)
But what if... you could already use it ? 🤭

Prerequisites

  • Have the newer version of powershell installed.
    If you plan on using the old one, replace pwsh with powershell

How ?

  1. Open your powershell
  2. Type notepad $PROFILE (can be another profile btw, more info here)
  3. Add the following :
function sudo {
    # Create a command line string with properly escaped arguments
    $escapedArgs = @()
    foreach ($arg in $args) {
        if ($arg -match '\s') {
            # If argument contains spaces, wrap it in quotes and escape internal quotes
            $escapedArg = '"' + ($arg -replace '"', '\"') + '"'
        } else {
            # Just escape internal quotes
            $escapedArg = $arg -replace '"', '\"'
        }
        $escapedArgs += $escapedArg
    }
    
    $command = $escapedArgs -join ' '
    
    # Base64 encode the command to avoid PowerShell parsing
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command + "; pause")
    $encodedCommand = [Convert]::ToBase64String($bytes)
    
    # Use Start-Process to execute the command in a new elevated PowerShell instance
    Start-Process pwsh -ArgumentList @("-ExecutionPolicy", "Bypass", "-EncodedCommand", $encodedCommand) -Verb RunAs
}
  1. Reload your profile with . $PROFILE

Enjoy !

Usage

sudo net start MySQL80

sudo tree /F "C:\idk\look a space\wow it handles quotes as well\and no need to wrap the command in quotes aswell\crazy"

If you want the elevated powershell to be reusable, add "-NoExit" at the start of the argument list.
If you want the powershell to autoclose, delete + "; pause" in the $bytes definition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment