1

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.

Jimmy Collins
  • 3,294
  • 5
  • 39
  • 57

1 Answers1

4

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Thanks, I've tried this but now my code seems to return immediately without the batch file running? I've added the updated code in my question, would you mind taking a quick look? – Jimmy Collins Apr 29 '11 at 15:00
  • Yeah very weird. I can see that cmd.exe is faulting in the Event Viewer, not sure why. – Jimmy Collins Apr 29 '11 at 15:59
  • @Jimmy C: I've had the exact same issue -- ASP.NET just plain refuses to run another process as another user (it's OK if you don't specify `UserName` and `Password`). Have you found a solution to this? – kizzx2 May 26 '11 at 05:38
  • @kizzx2 - Since I was working on an internally facing application, I ended up changing the account on the resource pool in IIS to the user I want it to run under. – Jimmy Collins May 26 '11 at 14:32
  • @Jimmy C : I have set the IIS application pool identity to Administrator account but still not working, – sudheshna May 07 '12 at 08:55