I am trying to write a batch file for my users to run from their Vista machines with UAC. The file is re-writing their hosts file, so it needs to be run with Administrator permissions. I need to be able to send them an email with a link to the .bat file. The desired behavior is that when they right-click on the file and say Open, they will get one of those UAC dialogs that makes the screen go dark and forces them to answer whether they want to give the application permission to run as administrator. Instead, they are just seeing "Access denied" on the command line window.
Is this possible to do differently?
I know this is not a solution for OP, but since I'm sure there are many other use cases here, I thought I would share.
I've had problems with all the code examples in these answers but then I found : http://www.robotronic.de/runasspcEn.html
It not only allows you to run as admin, it checks the file to make sure it has not been tampered with and stores the needed information securely. I'll admit it's not the most obvious tool to figure out how to use but for those of us writing code it should be simple enough.
Ben Gripka's solution causes infinite loops. His batch works like this (pseudo code):
As you can see, this causes an infinite loop, if the VBS fails requesting admin privileges.
However, the infinite loop can occur, although admin priviliges have been requested successfully.
The check in Ben Gripka's batch file is just error-prone. I played around with the batch and observed that admin privileges are available although the check failed. Interestingly, the check worked as expected, if I started the batch file from windows explorer, but it didn't when I started it from my IDE.
So I suggest to use two separate batch files. The first generates the VBS that calls the second batch file:
The second, named "my_commands.bat" and located in the same directory as the first contains your actual commands:
This causes no infinite loops and also removes the error-prone admin privilege check.
You can't request admin rights from a batch file, but you could write a windows scripting host script in %temp% and run that (and that in turn executes your batch as admin) You want to call the ShellExecute method in the Shell.Application object with "runas" as the verb
Here's a one-liner I've been using:
Notes:
Here is my code! It looks big but it is mostly comment lines (the lines starting with ::).
Features:
Mapped folder check (Warn´s you if admin can´t access mapped drive)
Can be used as an external library (check my post at this topic: https://stackoverflow.com/a/30417025/4932683)
Just attach this to the end of your batch file, or save it as a library (check above)
Example on how to use it