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:

    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: