windowspowershellcmdadministratorpowershell-core

windows core run command with elevated privileges


There are a few options for standard user to run as Administrator (or any another user), however, even when logged as Administrator, some functions requires to run 'elevated'.

On a windows gui, just right click a .exe and select run as Administrator or even elevate 'cmd' or 'powershell'.

How can you get elevated privileges on Windows core?


Solution

  • Generally, to programmatically invoke an executable with elevation (Run as Administrator) on Windows, use the Start-Process cmdlet with -Verb RunAs.

    This applies equally to pwsh.exe, the PowerShell Core executable, so that in the simplest case you can write:

    # Open a new console window with PowerShell Core running with admin privileges.
    Start-Process -Verb RunAs pwsh
    

    If you wanted to wrap that in a convenience function that is also more robust and cross-edition on Windows (also works in Windows PowerShell):

    function Enter-AdminPSSession {
      Start-Process -Verb RunAs (Get-Process -Id $PID).Path
    }
    
    # Optionally also define a short alias name:
    # Note: 'psa' is a nonstandard alias name; a more conformant name would be
    #       the somewhat clunky 'etasn' 
    #       ('et' for 'Enter', 'a' for admin, and 'sn'` for session), analogous
    #       to built-in 'etsn' alias referring to 'Enter-PSSession'
    Set-Alias psa Enter-AdminPSSession
    

    If you want the function to also be cross-platform (to also work on Unix-like platforms):

    function Enter-AdminPSSession {
      if ($env:OS -eq 'Windows_NT') {
        Start-Process -Verb RunAs (Get-Process -Id $PID).Path
      } else {
        sudo (Get-Process -Id $PID).Path
      }
    }
    

    Important: Due to the cmdlets / utilities involved,


    If you additionally want the ability to run commands in the new session and optionally auto-close it, much more work is needed:

    You can download function Enter-AdminPSSession from this Gist, which:

    Assuming you have looked at the linked Gist's source code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install Enter-AdminPSSession directly as follows:

    irm https://gist.github.com/mklement0/f726dee9f0d3d444bf58cb81fda57884/raw/Enter-AdminPSSession.ps1 | iex
    

    Example calls (which assume that Set-Alias psa Enter-AdminPSSession has been called):

    psa
    
    psa -NoProfile -ExitOnSuccess { Set-ExecutionPolicy -Scope LocalMachine RemoteSigned }
    
    psa -Exit { Get-Content /etc/sudoers }