Search code examples
c#wmiwin32-process

How to start script(vbs) with WMI in C# code?


I need to start a Visual Basic script file by using WMI in a c# code.

I don't quite understand what is wrong with this piece of code? Result will be always 8 (Unknown failure). But for example notepad.exe can be started without failure.

        //Get the object on which the method will be invoked
        ManagementClass processClass = new ManagementClass("Win32_Process");

        //Create an array containing all arguments for the method
        object[] methodArgs = { "C:\\MyFolder\\Test.vbs arg1 arg2", null, null, 0 };

        //Execute the method
        object result = processClass.InvokeMethod("Create", methodArgs);

Solution

  • Scripts aren't executables - they are run by Windows Script Host, so you need to specify the path to cscript.exe or wscript.exe before the script name:

    object[] methodArgs = {   
                            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cscript.exe") + @" C:\MyFolder\Test.vbs arg1 arg2",
                            null,
                            null,
                            0
                          };