Sudo !! equivalent in PowerShell

23,348

Solution 1

$^ is a variable that expands to the last executed Powershell command.

You can run a command as another user using runas, so the following works:

runas /user:domain\administrator $^

To shorten that up a bit, you can do some magic with aliases. Take a look at this Technet article for more info.

EDIT: One caveat - $^ only executes the first command in a pipeline or multi-command line. If you need to redo an entire command that is peppered with pipes or semicolons, use Invoke-History instead (which defaults to the last full command in its entirety).

Solution 2

I have always though of JEA (Just Enough Administration) as an attempt to approximate some of the functionality of sudo. You can read about it here:

https://docs.microsoft.com/en-us/powershell/scripting/learn/remoting/jea/overview

Where is differs is that it uses PS remoting rather than applying to the local machine. This may be quite a critical difference, enough to push it too far away from sudo.

Elevating to account for User Account Control, using runas or something else, doesn't really fit well for me. It's more like a parallel of su -.

Share:
23,348

Related videos on Youtube

BlueGene
Author by

BlueGene

Updated on September 18, 2022

Comments

  • BlueGene
    BlueGene almost 2 years

    "Sudo !!" invokes previously executed command with administrator privileges in *nix shell. Is there an equivalent in PowerShell?

    • mivk
      mivk about 4 years
      See my answer here, using Powershell's Start-Process with the -Verb runas option.
  • Joey
    Joey about 13 years
    Actually, $^ is the first token of the previous command. If I dot-source a script with . ./foo.ps1 then $^ is .. This also means that arguments are not contained. Doing anything that exceeds a single token will not work this way.
  • Developer
    Developer about 13 years
    ok, does it ask for password after that ? I am trying to avoid embedding plaintext password in my script.
  • Hyppy
    Hyppy about 13 years
    Yes, it does. Unless you run the script as an administrator, you'll need to provide credentials to do anything that requires administrator privileges. You may want to look into something like Kixtart to tokenize an embedded password
  • Martin Brown
    Martin Brown almost 4 years
    The link's broken.
  • PollusB
    PollusB almost 3 years
    I totally agree. You can also offer only a short set of commands to the caller.