I have a script that runs in 2 parts. The first part requires admin access (updates HOSTS file and does some copying/overwriting). After that part finishes, I need to map a drive using the hostname alias the first part of the script updated.
I have figured out how to get the elevated privileges by using this SO Question. But mapping a drive (while in admin) maps a drive into the admin's session. I need to "de-elevate" back into user mode to run my second script.
This is a script I run at least once every day, and possibly multiple times per day. I am trying to create a solution that is just 1 .bat file, if possible. For reasons, the scripts are written in perl.
Things I have tried:
TLDR: How do I de-elevate to user mode from admin mode in a batch file?
Yes, you're able to run a batch file with administrative rights. Unfortunately, you can't do this directly from the batch file it self. You would need to first create a shortcut of that batch file and change the properties for that shortcut in order to make this work.
To prevent echoing a particular command in a batch file, insert an @ sign in front of the command. To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.
Your best bet is to use the best third party remote/local execution tool : Windows Sysinternals PSEXEC. You can supply credentials and accomplish what you need using PSEXEC! You can put PSEXEC commands into your batch file or vbs and have them run without a hitch. You can also call one command with PSEXEC elevated permission and the next without any elevation, while mixing credentials in a single unique batch file.
http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
If you're using 2 batch files, call the batch ElevatedBatch.cmd
with elevation by using Main.cmd
(which continues doing unelevated things):
@ECHO OFF
START /WAIT ElevatedBatch.cmd %1 %2 %3 %4 %5 %6 %7 %8 %9
REM here you can do unelevated stuff:
ECHO Running unelevated now
The parameter /WAIT
ensures that the script will wait until ElevatedBatch.cmd
has ended. For ElevatedBatch.cmd
you can use a template like this one to elevate it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With