running a batch file from another batch file as an admisitrator

548 views Asked by At

I need to run a batch file (setup.bat) which will call another batch file (make_dir.bat) which will create a folder in the "C:\Program Files" directory. This is for an internal installer. All the users will be logged in with their user names but will have local administrator rights. I've tried two approaches but neither work.

Approach 1:

SET PRGFILES=%programfiles%\mySoftware
SET admin=N
SET domain=%USERDOMAIN%\
IF /i "%domain%" EQU "%computername%\" set domain=
SET user=%domain%%username%
FOR /f "Tokens=*" %%a IN ('net localgroup administrators^|find /i "%user%"') DO SET admin=Y
IF "%admin%"=="Y" (
    MD "%PRGFILES%"
)

This says Access is denied

Approach 2:

runas /user:%Username% shell\make_dir.bat

where make_dir.bat is

md "%programfiles%\mySoftware"

This asks for the current username and password but somehow fails after that. I have checked that all users have local admin rights and can manually create a folder in their programfiles folder.

Thanks for the help.

1

There are 1 answers

1
gavenkoa On

I use such script to run .bat file as administrator, using JScript:

var batch = "fixuac.bat"

var fso = new ActiveXObject("Scripting.FileSystemObject");
var curdir = fso.GetParentFolderName(WScript.ScriptFullName);

var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;
var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
// var objWMIService = GetObject("winmgmts:" + "{impersonationLevel=impersonate}!\\" + "." + "\root\cimv2");
var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem", "WQL",
                                      wbemFlagReturnImmediately | wbemFlagForwardOnly);
var enumItems = new Enumerator(colItems);
var objItem = enumItems.item();
// http://en.wikipedia.org/wiki/Ver_(command)
var major_ver = objItem.Version.split(".")[0];

var objShell = new ActiveXObject("shell.application");
// http://msdn.microsoft.com/en-us/library/windows/desktop/gg537745.aspx
//                 Shell.ShellExecute method
// iRetVal = Shell.ShellExecute( sFile, [ vArguments ], [ vDirectory ], [ vOperation ], [ vShow ] )
// If (vShow==1) open the application with a normal window.
// Check for Vista and upper.
if (major_ver >= 6) {
    // Request admin permission.
    objShell.ShellExecute(batch, curdir, "", "runas", 1);
} else {
    objShell.ShellExecute(batch, curdir);
}