How to run batch script with admin privilege instead of right-clicking it and clicking 'run as administrator' programmatically?
Since right-clicking consumes time to compute the menu, I prefer a faster way to run batch script with admin privilege.
How to run batch script with admin privilege instead of right-clicking it and clicking 'run as administrator' programmatically?
Since right-clicking consumes time to compute the menu, I prefer a faster way to run batch script with admin privilege.
You can do it with vbs. All you need to do is add the following code to the beginning of the batch script:
>NUL 2>&1 REG.exe query "HKU\S-1-5-19" || (
ECHO SET UAC = CreateObject^("Shell.Application"^) > "%TEMP%\Getadmin.vbs"
ECHO UAC.ShellExecute "%~f0", "%1", "", "runas", 1 >> "%TEMP%\Getadmin.vbs"
"%TEMP%\Getadmin.vbs"
DEL /f /q "%TEMP%\Getadmin.vbs" 2>NUL
Exit /b
)
I hope it helps.
The command you're looking for is runas
- this allows you to run programs as a user different to your current one.
I'm not sure that allows you to script the password but, from memory, you can cache the credentials for later use.
To script the password will require a tool like psexec
(form Microsoft's PsTools
suite). You should be able to do something like:
psexec \\127.0.0.1 -u Administrator -p <admin-password> xyzzy
to run the xyzzy
command as admin.
I normally couldn't test that as our corporate protection software prevents that psexec
program from being created, due to its use in attack vectors. However, I've found a computer in the isolated test bed area which shows it in operation:
C:\> psexec \\172.16.1.100 -u Administrator -p NeverYouMind ipconfig
PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 172.16.1.100
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 172.16.1.1
ipconfig exited on 172.16.1.100 with error code 0.