简体   繁体   中英

Execute VBS Script With Command Prompt Arguments in C#

I have a .vbs script file that needs to be executed from a C# application. We would normally execute the vbs file from right-clicking it and selecting "Open With Command Prompt" so the user can input arguments and the script will take off.

With the code below I'm able to execute the vbs file but it still prompts for input:

var MyProcess = new Process();
MyProcess.StartInfo.FileName = @"MyVBSScript.vbs";
MyProcess.StartInfo.WorkingDirectory = @"C:\Folder\WhereVBS\FileLives";
MyProcess.StartInfo.Arguments = @"UserArgumentWithoutSpaces";
MyProcess.Start();
MyProcess.WaitForExit();
MyProcess.Close();

My goal is to bypass the prompt by passing an argument. Is there something I need to do in the VBS file or does something in my C# code need to change?

I'm not sure what the args are that you want to pass in but look at my HelloWorld example below. The args I have in this script are /admin or /user and a Case...Else to ensure that the script cannot be run without args. The commandline would be cscript.exe "C:\\Scripts\\Hello_with_Args.vbs" /admin if you want the process to be somewhat hidden and wscript.exe "C:\\Scripts\\Hello_with_Args.vbs" /admin if you want the user to see it. and use the MyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; or something like that to hide the command prompt window. Hope this helps.

'Hello_with_Args.vbs
Dim args
Set args = WScript.Arguments
If args.Count > 0 Then
    For i = 0 To args.Count - 1
        Select Case LCase(args.Item(i))
            Case "/admin"
                WScript.Echo "Hello World!!" & vbCrLf & "You passed the /admin arg."
            Case "/user"
                WScript.Echo "Hello World!!" & vbCrLf & "You passed the /user arg."
            Case Else
                WScript.Echo "You can only use the ""/admin"" or ""/user"" command line arg or do not specify an arg."
        End Select
    Next
Else
    Wscript.Echo "Hello World!!" & vbCrLf & "No command line args passed."
End If

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