sudo icon indicating copy to clipboard operation
sudo copied to clipboard

Rerun the last command as `sudo` (`sudo !!`)

Open TheBrenny opened this issue 7 months ago • 2 comments

Description of the new feature / enhancement

Consider adding a new command to the sudo syntax (sudo !!) to allow it to rerun the previous command in an elevated session.

Scenario when this would be used?

As a sysadmin, I often find myself hopping between shells and always forget which commands need an elevated prompt and which don't. My immediate action is to just run the command normally, and when that fails because I'm not elevated, I use sudo !! to try again.

Supporting information

No response

TheBrenny avatar Apr 25 '25 04:04 TheBrenny

Press ⬆, Home, and then type "sudo ". Same amount of keystrokes.

ghost avatar Apr 28 '25 20:04 ghost

The simplest workaround is to define a sudo function in your $PROFILE, like the one I use myself:

function sudo {
	begin {
		function convertToBase64EncodedString([string]$cmdLine) {
			[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($cmdLine))
		}
	}
	end {
		switch ($args[0]) {
			$null {
				sudo.exe pwsh -nol
				break
			}
			'!!' {
				$encoded = convertToBase64EncodedString "$(Get-History -c 1)"
				sudo.exe pwsh -e $encoded
				break
			}
			{ $_ -is [scriptblock] } {
				$encoded = convertToBase64EncodedString $_
				sudo.exe pwsh -e $encoded
				break
			}
			{ Get-Command $_ -Type Application -ErrorAction Ignore } {
				# pass as-is for native command
				sudo.exe $args
				break
			}
			{ Get-Command $_ -Type Cmdlet, ExternalScript, Alias -ErrorAction Ignore } {
				$encoded = convertToBase64EncodedString "$args"
				sudo.exe pwsh -e $encoded
				break
			}
			default {
				throw "Cannot find '$_'"
			}
		}
	}
}

8LWXpg avatar May 06 '25 15:05 8LWXpg

This looks like a duplicate of #6.

00-kat avatar Jun 01 '25 03:06 00-kat

I guess I gotta get better at using GitHub search.

/dupe #6

TheBrenny avatar Jun 01 '25 07:06 TheBrenny