views:

854

answers:

3

As part of an installer, I need to run a batch file from ANT. If I run cmd.exe as Administrator and run the batch file, all is well since it has the appropriate administrative privileges. When the batch file is executed from ant, it fails, the same way it does if I were to run the batch file without administrative privileges. My question is, how can I run this batch file in Administrative mode from my ANT script?

<exec executable="cmd.exe" output="dir.txt" dir="c:/bin/">
<arg line="/c service.bat install"/>
</exec>
+3  A: 

At least XP has a runas command which you can try to use, something like:

runas /u:%COMPUTERNAME%\Administrator "cmd /c service.bat install"

When invoked, it will ask for password on console.

UPDATE: half of year later, I have upgraded to Windows 7. Here runas cannot be used for privilege elevation, but Aaron Margosis has a solution:

// elevate.js -- runs target command line elevated
if (WScript.Arguments.Length >= 1) {
    Application = WScript.Arguments(0);
    Arguments = "";
    for (Index = 1; Index < WScript.Arguments.Length; Index += 1) {
        if (Index > 1) {
            Arguments += " ";
        }
        Arguments += WScript.Arguments(Index);
    }
    new ActiveXObject("Shell.Application").ShellExecute(Application, Arguments, "", "runas");
} else {
    WScript.Echo("Usage:");
    WScript.Echo("elevate Application Arguments");
}

Which perhaps could be embedded in the installer if needed. For end users though, the Script Elevation Power Toys is more convienent, as suggested by another answer.

Laurynas Biveinis
Oops, the question was about Vista. Well my answer is based on XP only, I am not sure if it applies to Vista.
Laurynas Biveinis
Just tried that on Vista. Did not work... Thanks for the suggestion. Any more ideas anyone?
Edward
+1  A: 

Turning off UAC seems to be the only option to allow this ant task to execute.

I tried making a shortcut to the batch file, and running that, since shortcuts can be set to 'run as administrator'. No luck there either as I get the prompt, but my batch file still fails out.

[http://www.mydigitallife.info/2007/02/17/how-to-open-elevated-command-prompt-with-administrator-privileges-in-windows-vista/][1]

Edward
+2  A: 

You could try the Script Elevation PowerToy. It adds an elevate command that can be used to elevate privileges on the command line.

R. Bemrose
As part of an installer I can't guarantee that this power toy in installed on the machine, unfortunately. For anyone who wants to fix this problem on their machine to make life a little easier, that is a great suggestion. Thanks.
Edward
Ah, right. I didn't consider that. Actually, Windows tends to treat programs with certain names as always needing admin privileges (setup.exe for instance)... I wonder if that's true for setup.bat.
R. Bemrose