Search code examples
windowspowershellwindows-terminal

get administrator privileges in PowerShell (Windows Terminal) from without running it as an administrator


Even if you are a authoritative user and you need to do something that requires extended privileges, I have to run the terminal again by right clicking it as choosing "Run as Administrator" unlike in Linux and other operating systems where we can take help of "su" or "sudo".

My question is : Is there any way to get the same terminal window as a administrator one?


Solution

  • To programmatically start an elevated new PowerShell session (with administrative privileges) on Windows - invariably in a new window - from an existing session, use:

    Note:

    • The command below invariably opens the elevated PowerShell instance in an - invariably new - regular console window (conhost.exe) - see next section for use from Windows Terminal.
    Start-Process -Verb RunAs (Get-Process -Id $PID).Path
    

    The above works in both PowerShell editions and uses the same executable that is running the current session; you can take a shortcut if you know the executable name and can assume it to be the first in $env:PATH when invoked by name only; for Windows PowerShell:
    Start-Process -Verb RunAs powershell
    and for PowerShell (Core) 7+:
    Start-Process -Verb RunAs pwsh

    See this answer for convenience functions, including for cross-platform use and the ability to pass commands to execute in the elevated session.


    To open the elevated session in Windows Terminal (also invariably in a new window):

    # As above, 'powershell.exe' or 'pwsh.exe' may do as the argument.
    # See below for Windows Terminal profile-related options.
    Start-Process -Verb RunAs wt.exe ('"{0}"' -f (Get-Process -Id $PID).Path)
    

    Note:

    • If the desired PowerShell executable is your Windows Terminal's default profile, you can omit the argument after wt.exe

      # Launch the elevated session with the shell configured as
      # the default profile.
      Start-Process -Verb RunAs wt.exe
      
    • If you want to target a specific Windows Terminal profile, pass its name (or GUID) case-exactly to the -p (--profile) parameter; e.g.:

      # Launch the elevated session with the "Windows PowerShell" profile.
      Start-Process -Verb RunAs wt.exe '-p "Windows PowerShell"'