Simple method to run a batch as Administrator using javascript

前端 未结 1 1625
夕颜
夕颜 2021-01-20 08:13

I want to derive a simple reliable method to auto elevate a running batch without using extra VBS files or elevated shortcuts, proposed in other threads. Calling the UAC dia

相关标签:
1条回答
  • 2021-01-20 08:40

    I fixed the script, and now it runs great. As per my research, this is the simplest reliable way to dynamically give a regular user Administrator privileges for the duration of that Cmd session in a running batch published anywhere.

    It doesn't require using functions, hybrid batch & VBS constructs, extra files or elevated shortcuts. It is native to Windows. Users can add their own task code in the :usercode section to run by the batch.

    @echo off
    setlocal EnableDelayedExpansion
    :: test and acquire admin rights
    cd /d %~dp0 & echo/
    if not "%1"=="UAC" (
        >nul 2>&1 net file && echo Got admin rights || (echo No admin rights & ^
    MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute("%~snx0", 'UAC', '', 'runas', 1);close();"))
    :: re-test admin rights
    echo/ & >nul 2>&1 net file && (echo Got admin rights & echo/) || (echo No admin rights. Exiting... & goto :end)
    
    :usercode
    :: add your code here
    echo Performing admin tasks
    echo Hello >C:\test.txt
    
    :end
    timeout /t 5 >nul
    exit /b
    
    0 讨论(0)
提交回复
热议问题