4

In my VB-NET application I need to run a batch file as administrator.

So far I use this code but can't remember how to use runas:

process.start("filelocation.bat")

Any help is apreciated.

Andreas
  • 5,393
  • 9
  • 44
  • 53
Chris Wilson
  • 59
  • 1
  • 1
  • 7
  • Possible duplicate of http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically – Timiz0r Jul 16 '12 at 13:03

2 Answers2

4
Try
    Dim procInfo As New ProcessStartInfo()
    procInfo.UseShellExecute = True
    procInfo.FileName = (FileLocation)
    procInfo.WorkingDirectory = ""
    procInfo.Verb = "runas"
    Process.Start(procInfo)
Catch ex As Exception
    MessageBox.Show(ex.Message.ToString())
End Try
user1244772
  • 294
  • 4
  • 9
  • 22
2

You could try with this code:

Dim proc as ProcessStartInfo  = new ProcessStartInfo()
proc.FileName = "runas"
proc.Arguments = "/env /user:Administrator filelocation.bat"
proc.WorkingDirectory = "your_working_dir"
Process.Start(proc)

This code will ask the Administrator password and the start the execution of your batch file

EDIT: This is an alternative without the cmd window

Dim proc as ProcessStartInfo  = new ProcessStartInfo()
proc.FileName = "filelocation.bat"
proc.WorkingDirectory = "your_working_dir"  // <- Obbligatory
      proc.UseShellExecute = False
      proc.Domain = userDomain // Only in AD environments?
      proc.UserName = userName
      proc.Password = securePassword
Process.Start(proc)

It's a little more complicated because you need to get the input values (userName, Password, domain) before using this code and the password is a SecureString that you need to build in a dedicated way

Dim securePassword as New Security.SecureString()
For Each c As Char In userPassword
    securePassword.AppendChar(c)
Next c
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Hi, This doesnt quite run as I would like. I need it to run as admin but first as the users permission in the small dialogue box, not through cmd. Thanks – Chris Wilson Jul 16 '12 at 12:10
  • Updated my answer. This alternative solution requires you get the inputs in some way from your user – Steve Jul 16 '12 at 13:34