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

后端 未结 15 949
陌清茗
陌清茗 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:18

    Using powershell.

    If the cmd file is long I use a first one to require elevation and then call the one doing the actual work.

    If the script is a simple command everything may fit on one cmd file. Do not forget to include the path on the script files.

    Template:

    @echo off
    powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c " comands or another script.cmd go here "'"
    

    Example 1:

    @echo off
    powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\BIN\x.ps1"'"
    

    Example 2:

    @echo off
    powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c "c:\bin\myScript.cmd"'"
    

提交回复
热议问题