5

I have create a batch file which use to install my program as windows services. Content of the batch file:

> C:\Project\Test\InstallUtil.exe
> "C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe"

Currently it needs the user to right-click the batch file and 'Run as Administrator' in order to success. How do we avoid 'Run as Administrator'? I mean can we use some command in the batch file to tell Windows to run this batch file as administrator?

Riaan van Zyl
  • 538
  • 8
  • 17
Wilson
  • 162
  • 1
  • 1
  • 11

1 Answers1

9

This way worked for me in the past:

string exe = @"C:\Project\Test\InstallUtil.exe";
string args = @"C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe";
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows
psi.FileName = @"cmd.exe";
psi.Verb = "runas"; //This is what actually runs the command as administrator
psi.Arguments = "/C " + exe + " " + args;
try {
    var process = new Process();
    process.StartInfo = psi;
    process.Start();
    process.WaitForExit();
}
catch (Exception){
    //If you are here the user clicked decline to grant admin privileges (or he's not administrator)
}

Note that I'm running the commands in your batch file directly here, but of course you can also run the batch file itself:

string bat = @"C:\path\to\your\batch\file.bat";
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows
psi.FileName = @"cmd.exe";
psi.Verb = "runas"; //This is what actually runs the command as administrator
psi.Arguments = "/C " + bat;
Djensen
  • 1,337
  • 1
  • 22
  • 32
Master_T
  • 7,232
  • 11
  • 72
  • 144
  • How can we run this on client's machine in admin mode? – Amit Sinha Oct 19 '17 at 11:45
  • @EnigmaticMind: I don't understand your question... the code already runs the commands in admin mode. What is your problem exactly? – Master_T Oct 19 '17 at 12:51
  • I put above code in web application. and in path of bat file I gave server IP(clients IP).+ path It was not working. So the question was that if code works for web application or not. – Amit Sinha Oct 19 '17 at 14:18
  • You cannot run a process/bat on a different machine with this code, this code is for running it on the local machine. – Master_T Oct 19 '17 at 14:27
  • for my usage I need to set "psi.UseShellExecute = true;" too. I also created a new process and set psi as process.startInfo. After that execute process.Start(). – Kai W Dec 09 '22 at 10:12