Jimmy Collins
Jimmy Collins

Reputation: 3304

Ensuring Process.Start() runs under the logged in user

I'm running a batch file from some ASP.NET/C# code on a web server. Basically the batch file performs some test automation tasks on a VM using tools like psloggedon and pexec.

If I run the batch file manually when I'm logged into the server under an administrative account, it works fine.

My problem comes when I run it from my code (below), it seems to run under the 'SYSTEM' account, and psloggedon etc. don't seem to work correctly.

Code

     Process p = new Process();
     p.StartInfo.FileName = "C:\SetupVM.bat";
     p.Start();
     p.WaitForExit();

I've got this in my web.config, it doesn't seem to make any differance?

<identity impersonate="true" userName="Administrator" password="myadminpassword"/>

Is there anyway I can ensure the batch file runs under the 'Administrator' account?

UPDATED CODE

      Process p = new Process();
      p.StartInfo.FileName = "C:\\SetupVM.bat";
      p.StartInfo.UserName = "Administrator";
      p.StartInfo.UseShellExecute = false;
      p.StartInfo.WorkingDirectory = "C:\\";

      string prePassword = "myadminpassword";
      SecureString passwordSecure = new SecureString();
      char[] passwordChars = prePassword.ToCharArray();
      foreach (char c in passwordChars)
      {
          passwordSecure.AppendChar(c);
      }
      p.StartInfo.Password = passwordSecure;
      p.Start();
      p.WaitForExit();

From MSDN:

When UseShellExecute is false, you can start only executables with the Process component.

Maybe this is the issue as I'm trying to run a .bat file?

Thanks.

Upvotes: 1

Views: 4749

Answers (1)

Oded
Oded

Reputation: 499002

You can provide the username and password to the StartInfo:

Process p = new Process();
p.StartInfo.FileName = "C:\SetupVM.bat";
p.StartInfo.UserName = "Administrator";
p.StartInfo.Password = "AdminPassword";
p.Start();
p.WaitForExit();

See the documentation for ProcessStartInfo.

Upvotes: 4

Related Questions