How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

后端 未结 15 944
陌清茗
陌清茗 2020-11-22 03:59

I want my batch file to only run elevated. If not elevated, provide an option for the user to relaunch batch as elevated.

I\'m writing a batch file to set a system v

15条回答
  •  无人及你
    2020-11-22 04:26

    I wrote gsudo, a sudo for windows: that elevates in the current console (no context switching to a new window), with a credentials cache (reduced UAC popups), and also elevates PowerShell commands.

    It allows to elevate commands that require admin privileges, or the whole batch, if you want. Just prepend gsudo before anything that needs to run elevated.

    Example batch file that elevates itself using gsudo:

    EDIT: New one liner version that works with any windows language and avoids whoami issues:

    net session >nul 2>nul & net session >nul 2>nul || gsudo "%~f0" && exit /b || exit /b
    :: This will run as admin ::
    

    Alternative (original version):

    @echo off
      rem Test if current context is already elevated:
      whoami /groups | findstr /b BUILTIN\Administrators | findstr /c:"Enabled group" 1> nul 2>nul && goto :isadministrator
      echo You are not admin. (yet)
      :: Use gsudo to launch this batch file elevated.
      gsudo "%~f0"
      goto end
    :isadministrator
      echo You are admin.
      echo (Do admin stuff now).
    :end
    

    Install:

    • via chocolatey: choco install gsudo
    • or scoop: scoop install gsudo
    • or grab it from github: https://github.com/gerardog/gsudo

    See gsudo in action: gsudo demo

提交回复
热议问题