0
votes

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.

1
Sorry, twice I've tried using the 'code' function. It displays correcly in the preview pane but not when I post it!!?? - user1486746
Put a line break/carriage return between "My code:" and "Dim..." to get the code to display correctly. I'd do it myself but its too minor an edit. - Andrew Lee

1 Answers

0
votes

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 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()