0

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.

phuclv
  • 37,963
  • 15
  • 156
  • 475
Louis55
  • 408
  • 6
  • 17
  • Possible duplicate of [How run file .bat as admin](https://stackoverflow.com/questions/26430564/how-run-file-bat-as-admin) – phuclv Jan 04 '19 at 05:25
  • many other duplicates: [How do you run a command as an administrator from the Windows command line?](https://stackoverflow.com/q/5944180/995714), [How to run 'sudo' command in windows](https://stackoverflow.com/q/9652720/995714), [How to create a batch file to run cmd as administrator](https://stackoverflow.com/q/11525056/995714), [How to run an application as "run as administrator" from the command prompt?](https://stackoverflow.com/q/8249705/995714) – phuclv Jan 04 '19 at 05:27

2 Answers2

2

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.

Louis55
  • 408
  • 6
  • 17
0

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.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953