windows core run command with elevated privileges

淺唱寂寞╮ 提交于 2019-12-06 22:05:42

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: 'psadmin' 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)
Set-Alias psadmin 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,

  • on Windows, the new session invariably opens in a new console window.

    • The fact that the new session is an admin session is reflected in its window's title (prefix Administrator:)
  • on Unix (Linux, macOS), the new session invariably opens in the same console (terminal) window.

    • On Unix there is no obvious indicator that an admin session has been entered; running whoami is a quick way to test for that (returns root in an admin session); a better solution would be to modify the prompt function to reflect an admin session in the prompt string.

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

If you download script Enter-AdminPSSession.ps1 (an MIT-licensed Gist), you can run commands such as the following:

# Example: Synchronously run an MSI installer with elevation
#          and exit on completion.
Enter-AdminPSSession -Exit { Start-Process msiexec -Args '/qn /i package.msi' }

# Check for success via $LASTEXITCODE
if ($LASTEXITCODE -ne 0) { Throw "Installation failed." }

Additionally, the script:

  • prefixes the prompt string in interactive elevated sessions with [admin] 

  • ensures that the calling session's current location (working directory) is also the elevated session's current location.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!