• Home
  • About
  • Contact
  • Speaking

sudo !! - run last command in elevated PowerShell prompt

by Piotr Stapp — on powershell 06 Jun 2016

Last week I have a lot of fun with docker on windows, but I have one small problem. I usually run PowerShell in standard mode, without admin rights. And from time to time I want to restart service, run docker command or ... - run the previous command in the elevated prompt. In Linux, there is a sudo !!. But in PowerShell, there is no even built-in sudo.

A few months ago I described how to run sudo command in PowerShell (more in Run sudo in Windows). But I was still missing sudo !!.
Today I found a solution.

Using Get-History

I need a good name for my function. I decided to name it: f--k. I usually say this word, when I forgot about admin rights.

It is really easy to create we just need to get last invoked command using Get-History ‎Cmdlet:

function f--k  
{
    $cmd = (Get-History ((Get-History).Count))[0].CommandLine
    Write-Host "Running $cmd in $PWD"
    sudo powershell -NoExit -Command "pushd '$PWD'; Write-host 'cmd to run: $cmd'; $cmd"
}

Linux style

Now we can modify original sudo function to accept !!:

function sudo  
{
    if($args[0] -eq '!!')
    {
         f--k;
    }
    else
    {
       $file, [string]$arguments = $args;
       $psi = new-object System.Diagnostics.ProcessStartInfo $file;
       $psi.Arguments = $arguments;
       $psi.Verb = "runas";
       $psi.WorkingDirectory = get-location;
       [System.Diagnostics.Process]::Start($psi);
    }
}

And now I am happy Windows user with Linux styled command.


Follow @ptrstpp950

0%
sudo !! - run last command in elevated PowerShell prompt
words - read.
Recent Posts:

Comments

comments powered by Disqus
Piotr Stapp Author

Piotr Stapp

Developer, engineer, craftsmen, speaker & biker. User of all useful technologies. Believe in people not papers. DevOps & automation adept. In love with web technologies. I speak here for myself only.

Previous post ReAttach - how to easily (re)attach the debugger in Visual Studio In more complicated projects, simple F5 doesn't compile&debug. In cases where you're working with IIS (w3wp process)…
Next post How to split monolith solution - part 1: common myths Do you have a big and heavy solution? Do you want to split it? Are you afraid? I will…
All content copyright Reset your code © 2016 • All rights reserved.
Proudly published with Ghost