简体   繁体   中英

VB.Net - execute vbscript using process with 'run as administrator'

I have a vbscript file that I want to run in my vb.net application. In the application, the script 'must' use a process. The reason is that it's actually being called from a windows process. In order for me to execute the vbscript manually, I have to right-click on the shortcut and select 'run as administrator'.

How can I emulate this using vb.net? Currently the execution works because I tested it with it only creating a text file. Also, I want to assume that the user is in the administrators group and don't want them to have to login each time because it will execute every minute.

My code:

Dim foo As New System.Diagnostics.Process
foo.StartInfo.WorkingDirectory = "c:\"
foo.StartInfo.RedirectStandardOutput = True
foo.StartInfo.FileName = "cmd.exe"
foo.StartInfo.Arguments = "%comspec% /C cscript.exe //B //Nologo C:\aaa\test.vbs"
foo.StartInfo.UseShellExecute = False
foo.StartInfo.CreateNoWindow = True
foo.Start()
foo.WaitForExit()
foo.Dispose()

Thanks.

The class ProcessStartInfo has two properties that can be used to define the user name that will run your script

ProcessStartInfo.UserName
ProcessStartInfo.Password

Please note as from MSDN: The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\\system32. The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\\system32.

The Password property is of type SecureString. This class need a special initialization code like this:

  ' Of course doing this will render the secure string totally 'insecure'
  Dim pass As String = "Password"
  Dim passString As SecureString = New SecureString()
  For Each c As Char In pass
     passString.AppendChar(ch)
  Next   

So your code could be changed in this way

Dim foo As New System.Diagnostics.Process   
foo.StartInfo.WorkingDirectory = "c:\"   
foo.StartInfo.RedirectStandardOutput = True   
foo.StartInfo.FileName = "cmd.exe"   
foo.StartInfo.Arguments = "%comspec% /C cscript.exe //B //Nologo C:\aaa\test.vbs"   
foo.StartInfo.UseShellExecute = False   
foo.StartInfo.CreateNoWindow = True   
foo.StartInfo.UserName = "administrator"
foo.StartInfo.Password = passString
foo.Start()   
foo.WaitForExit()   
foo.Dispose()  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM